O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required