This blog post was originally posted on my blogpost blog at this URL,
and was later migrated to this place. There may be some comments at the original URL.
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.)