Pattern matching

Slice and dice is defined as the process of breaking something down (for example, information) into smaller parts to examine and understand it. You can get more information about slice and dice at:

http://dictionary.reference.com/browse/slice-and-dice

Let's see this technique in action. We will try to count the number of elements in List. There is already a length method defined on Lists:

scala> List(1,2,3).length
res0: Int = 3

Rolling out one of our own list teaches us something:

object Count 
extends App {
def count(list: List[Int]): Int = list match {
  case Nil => 0  // 1
  case head :: tail => 1 + count(tail) // 2
}
val l = List(1,2,3,4,5)
println(count(l)) // prints 5 
 }

The preceding code counts the number of elements in ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.