Scala for Multicore

UPMARC Multicore Computing Summer School 2011

Philipp Haller, EPFL and Stanford University

Code Example: Pattern Matching

Experimenting with pattern matching in Scala's interpreter (REPL). Below is both the code entered into the REPL as well as the REPL's output.

abstract class Tree[+T]
case class Binary[T](el: T, left: Tree[T], right: Tree[T]) extends Tree[T]
case object Empty extends Tree[Nothing]
val tree = Binary(6, Binary(5, Empty, Empty), Binary(10, Empty, Empty))
tree match {
 case Binary(el, l, r) => println(l)
}

def inOrder[T](t: Tree[T]): List[T] = t match {
 case Empty => List()
 case Binary(el, l, r) => inOrder(l) ::: List(el) ::: inOrder(r)
}
inOrder(tree)

scala> inOrder(tree)
res1: List[Int] = List(5, 6, 10)