Why does the foldLeft
take
f: (B, A) => B
and foldRight take
f: (A, B) => B
foldLeft
could have been written to take f: (A, B) => B.
I am trying to understand the reasoning for the difference in the order of parameters.
It's supposed to show you the direction of the aggregation. FoldLeft aggregates from left to right, so you can imagine the accumulator B as bunching up stuff on the left side as it approaches each A:
If you have something like:
Vector(1,2,3,4,5).foldLeft(0)((b,a) => b + a)
Then you get this behavior
B ...As...
---------------
(0), 1, 2, 3, 4, 5
(0+1), 2, 3, 4, 5
(0+1+2), 3, 4, 5
(0+1+2+3), 4, 5
(0+1+2+3+4), 5
(0+1+2+3+4+5)
FoldRight, on the other hand, aggregates things from the right side. So if you have something like:
Vector(1,2,3,4,5).foldRight(0)((a,b) => a + b)
Then you get this behavior
...As... B
-----------------
1, 2, 3, 4, 5 (0)
1, 2, 3, 4, (5+0)
1, 2, 3, (4+5+0)
1, 2, (3+4+5+0)
1, (2+3+4+5+0)
(1+2+3+4+5+0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With