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).
Discovers lambdas. Has an “aha!” moment. Likes the warm fuzzy feeling he gets while rewriting the above with a lambda.
Discovers fold. Another “aha!” moment. Likes immutability.
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.
Learns to love his symbols.
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 (
view method that fuses multiple passes into one, and makes computation more efficient (well, at least in some cases.)
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.
This blog post was originally posted at my Blogspot blog at this URL.