Scala foldLeft example

If you haven’t seen curried functions before, the syntax for foldLeft looks pretty weird:

List(1, 2, 3)
  .foldLeft(0)((x, y) => { x + y })

res108: Int = 6

The first foldLeft argument is the initial value (0), and the second is a function to combine two values (0 + 1, then 1 + 2, then 3 + 3).

scala> List(1, 2, 3).foldLeft(0)_
res110: ((Int, Int) => Int) => Int = 

One of the neat things about this style of programming is that you can have the code that sets the initial value be far afield from the code that provides the summing operation (this is useful if you’re defining events that touch a model – the model could expose defaults this way, while delegating event handling to other classes)

The syntax for this is a bit weird, and the type that results is nearly incomprehensible:

val y = List(1, 2, 3).foldLeft(0)_
y: ((Int, Int) => Int) => Int = 

But, it works just liked you’d expect:

 y( (a, b) => a + b )
res111: Int = 6

How is this different from “reduce”? See here:

List(1, 2, 3).reduce( (x, y) => x + y )

Reduce is simpler, and is called without the default value (if you weren’t previously familiar with foldLeft, you might actually expect it’s signature to match the example above!)