Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of parameters to foldright and foldleft in scala

Tags:

scala

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.

like image 275
rufus16 Avatar asked Mar 21 '23 18:03

rufus16


1 Answers

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)
like image 89
dhg Avatar answered Apr 01 '23 20:04

dhg