Cascading
Often it is useful to execute one transformation after another to form a cascade of method calls on successive sequences obtained from consecutive transformations.
For example, suppose we want to compute the sum of the squares of a sequence of integers:
scala> a
res: Array[Int] = Array(752, 884, 995, 462, 126, 632, 445)
This is easy – first map to obtain the squares and then reduce to obtain the sum of squares:
scala> a.map(x => x*x).reduce(_ + _)
res: Int = 3163754
Or suppose we want to compute the sum of squares of all even integers.
No problem – first filter to get the even integers, then map to get the squares, and finally reduce to get the sum:
scala> a.filter(_ % 2 == 0).map(x => x*x).reduce(_ + _)
res: Int = 1975704
The term cascading comes from the fact that for better readability such transformations are best written one after one another on separate lines (with comments!), so the transformations form a “cascade”:
val result = a.filter(_ % 2 == 0) // get even elements
.map(x => x*x) // square
.reduce(_ + _) // sum up
Note
Sometimes, copying multi-line examples into the Scala REPL causes problems
because the console tries to execute each line independently.
In such a situation you can wrap the multi-line expression
in braces {
}
before giving it to the console. For example:
scala> {
| a.filter(_ % 2 == 0) // get even elements
| .map(x => x*x) // square
| .reduce(_ + _) // sum up
| }
res: Int = 1975704