Skip to content

Instantly share code, notes, and snippets.

@cgopalan
Created September 23, 2011 19:18
Show Gist options
  • Save cgopalan/1238210 to your computer and use it in GitHub Desktop.
Save cgopalan/1238210 to your computer and use it in GitHub Desktop.
Case Classes and Pattern Matching
object IntTreeTest {
abstract class IntTree
case object EmptyTree extends IntTree
case class Node(elem: Int, left: IntTree, right: IntTree) extends IntTree
def contains(t: IntTree, v: Int): Boolean = t match {
case EmptyTree => false
case Node(e, l, r) =>
if (v < e) contains(l, v)
else if (v > e) contains(r, v)
else true
}
def insert(t: IntTree, v: Int): IntTree = t match {
case EmptyTree => Node(v, EmptyTree, EmptyTree)
case Node(e, l, r) =>
if (v < e) Node(e, insert(l, v), r)
else if (v > e) Node(e, l, insert(r, v))
else t
}
def main(args: Array[String]) {
val t = insert(insert(insert(insert(insert(EmptyTree, 11), 1), 20), 18), 25)
println("Tree is: " + t)
println("Does Tree contain 20?: " + (if (contains(t, 20)) "Yes" else "No"))
println("Does Tree contain 15?: " + (if (contains(t, 15)) "Yes" else "No"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment