When should I use reduceLeft, reduceRight, foldLeft, foldRight, scanLeft or scanRight?
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
scan is like fold but also emits all intermediate valuesreduce doesn't need an initial value which sometimes is a little harder to findfold needs an initial value that is a little harder to find:
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