Skip to content

Instantly share code, notes, and snippets.

Created December 15, 2012 16:05
Show Gist options
  • Save anonymous/4296663 to your computer and use it in GitHub Desktop.
Save anonymous/4296663 to your computer and use it in GitHub Desktop.
Scala program, defining a tree with case classes and traversing it via pattern matching.
abstract class Tree
case class Leaf(value: String) extends Tree
case class Branch(left: Tree, right: Tree) extends Tree
def walk(t: Tree): Unit =
t match {
case Branch(Stub, _) => println("branch-with-stub-on-the-left")
case Branch(left, right) => {
println("\nbranch-leaf")
walk(left)
walk(right)
}
case Leaf(v) => printf("\tleaf: %s\t", v)
}
walk(Branch(
Leaf("A"), Branch(
Branch(Leaf("D"),Leaf("B")), Leaf("C"))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment