Difference between fold and foldLeft or foldRight?

Short answer:

foldRight associates to the right. I.e. elements will be accumulated in right-to-left order:

List(a,b,c).foldRight(z)(f) = f(a, f(b, f(c, z)))

foldLeft associates to the left. I.e. an accumulator will be initialized and elements will be added to the accumulator in left-to-right order:

List(a,b,c).foldLeft(z)(f) = f(f(f(z, a), b), c)

fold is associative in that the order in which the elements are added together is not defined. I.e. the arguments to fold form a monoid.

Leave a Comment