|
|
|
|
|
by rybosome
4703 days ago
|
|
This is why I love pattern matching in languages that support it - typing is just one of the things on which they can switch. As the Scala website puts it (paraphrasing), "Pattern matching is switch on steroids!" Here is how you would return all leaf values in a binary tree in Scala: case class Node
case class Fork(left: Node, right: Node) extends Node
case class Leaf(value: Int) extends Node
def getValues(node: Node): List[Int] = node match {
case f: Fork => getValues(f.left) ++ getValues(f.right)
case l: Leaf => List(l.value)
}
EDIT: Would actually be more idiomatic in Scala to extract the values from the case classes rather than just matching on type...yet another wonderful feature of pattern matching. Coded as follows: def getValues(node: Node): List[Int] = node match {
case Fork(left, right) => getValues(left) ++ getValues(right)
case Leaf(value) => List(value)
}
|
|