Consider the set of natural numbers[12].
sealed trait Natural final case object Zero extends Natural final case class Succ(s: Natural) extends Natural
We can now write a function to add two natural numbers.
def add(x: Natural, y: Natural): Natural = x match { case Zero => y case Succ(t) => add(t, Succ(y)) } scala> val k = add(Succ(Succ(Zero)), Succ(Zero)) // add 2 1 k: Natural = Succ(Succ(Succ(Zero)))
We destructure algebraic data types using pattern matching — the
case
and match
keywords.
We could write many functions over this algebraic data type.