Understanding foldLeft in scala

As I’m working on some scala code the last few weeks, i have come across some functions in the scala api that I didn’t understand right away. One of those functions was foldLeft, FoldLeft is a relative easy method, but the scaladoc is not quite clear.

Applies a binary operator to a start value and all elements of this list, going left to right.

What the method actually does is apply a method on all the elements of a Sequence and accumulating it a variable. The initial value of that variable is give as first parameter, the second parameter is the function you apply.
In java it would like this

T accumulator = initialValue;
for(X listItem : list){
    accumulator = method(accumulator, listItem);
}
return accumulator;

Take is an integer and method does “accumulator + listItem”, we get a method that adds all integers with eachother starting from the initial value.

val list = List(1,2,3)
list.foldLeft(0)(_ + _)

The first parameter of the function given as argument is the accumulator, the second is the current value (or listItem in the java example). foldLeft results in 6.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>