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 the list. We match the list against two possible cases, which are as follows:
- The base case: The list is
Nil
, and an empty list matchesNil
as it has zero elements, we return0
. - The general case: This is a list that has one or more elements...