foldLeft and foldRight, a Scala language concept
Last updated
A 'fold' allows you to perform the equivalent of a for-loop, but with a lot less code.
Becomes:
So you can see how ta Scala solution that is immutable can be represented in a mutable form. Reverse is also possible.
The big difference is that to the user it is immutable, because you only specify the next value by adding an item to an accumulator.
This presents many possibilities, most important of which is to be able to develop code in a highly predictable and obvious manner, whereas in standard for-loops, many complications can arise (wrong indices, unexpected mutations).
And in an immutable fashion:
The rule of thumb is: if you want a single result, use `foldLeft`, if you want a set of intermediate results, use scanLeft and scanRight.