The task is simple. You have a collection of document objects. You have to calculate the sum of their lengths. (This post on stackoverflow triggered me to write this.)

This is how Scala programmers, at various stages of their “evolution”, might approach this problem:

Enjoys type inference and absence of semicolons, and overall cleaner syntax (compared to Java).

var total = 0
for (doc <- docs) {
  total += doc.length
}
total

Discovers lambdas. Has an “aha!” moment. Likes the warm fuzzy feeling he gets while rewriting the above with a lambda.

var total = 0
docs.foreach(doc => total += doc.length)
total

Discovers fold. Another “aha!” moment. Likes immutability.

docs.foldLeft(0)((accum, current) => accum + current.length)

Underscore! The holy underscore! Loves how it removes the need for inventing new variable names every now and then, and how it makes code shorter.

docs.foldLeft(0)(_ + _.length)

Learns to love his symbols.

(0 /: docs)(_ + _.length)

Discovers type-classes. Yet another “aha!” moment; probably one of the biggest in his Scala/FP journey. Discovers methods like ‘sum’ which use this concept (sum uses Numeric type-class).

docs.map(_.length).sum

Discovers the view method that fuses multiple passes into one, and makes computation more efficient (well, at least in some cases.)

docs.view.map(_.length).sum

Starts tinkering with the arcane world of Scalaz. Discovers more general concepts such as monoid. More “aha!”s. Adds a few new functions to his toolbox.

docs.foldMap(_.length)