Reduce, fold or scan (Left/Right)?

前端 未结 3 687
孤城傲影
孤城傲影 2020-11-28 00:35

When should I use reduceLeft, reduceRight, foldLeft, foldRight, scanLeft or scanRight?

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 00:54

    For the collection x with elements x0, x1, x2, x3 and an arbitrary function f you have the following:

    1. x.reduceLeft    (f) is f(f(f(x0,x1),x2),x3) - notice 3 function calls
    2. x.reduceRight   (f) is f(f(f(x3,x2),x1),x0) - notice 3 function calls
    3. x.foldLeft (init,f) is f(f(f(f(init,x0),x1),x2),x3) - notice 4 function calls
    4. x.foldRight(init,f) is f(f(f(f(init,x3),x2),x1),x0) - notice 4 function calls
    5. x.scanLeft (init,f) is f(init,x0)=g0
                              f(f(init,x0),x1) = f(g0,x1) = g1
                              f(f(f(init,x0),x1),x2) = f(g1,x2) = g2
                              f(f(f(f(init,x0),x1),x2),x3) = f(g2,x3) = g3
                              - notice 4 function calls but also 4 emitted values
                              - last element is identical with foldLeft
    6. x.scanRight (init,f) is f(init,x3)=h0
                              f(f(init,x3),x2) = f(h0,x2) = h1
                              f(f(f(init,x3),x2),x1) = f(h1,x1) = h2
                              f(f(f(f(init,x3),x2),x1),x0) = f(h2,x0) = h3
                              - notice 4 function calls but also 4 emitted values
                              - last element is identical with foldRight
    

    In conclusion

    • scan is like fold but also emits all intermediate values
    • reduce doesn't need an initial value which sometimes is a little harder to find
    • fold needs an initial value that is a little harder to find:
      • 0 for sums
      • 1 for products
      • first element for min (some might suggest Integer.MAX_VALUE)
    • not 100% sure but it looks like there are these equivalent implementations:
      • x.reduceLeft(f) === x.drop(1).foldLeft(x.head,f)
      • x.foldRight(init,f) === x.reverse.foldLeft(init,f)
      • x.foldLeft(init,f) === x.scanLeft(init,f).last

提交回复
热议问题