Skip to content

Instantly share code, notes, and snippets.

@asarkar
Created June 10, 2015 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asarkar/f14a8672caad99bb7dab to your computer and use it in GitHub Desktop.
Save asarkar/f14a8672caad99bb7dab to your computer and use it in GitHub Desktop.
Scala Pattern Matching Demo
sealed abstract class BinaryTree
case class BinTreeLeaf(value: Int) extends BinaryTree
case class BinTreeNode(left: BinaryTree, right: BinaryTree) extends BinaryTree
def leafSum(tree: BinaryTree): Int = tree match {
case node: BinTreeNode => leafSum(node.left) + leafSum(node.right)
case leaf: BinTreeLeaf => leaf.value
}
"Method leafSum" should "traverse a binary tree in order" in {
/**
* .
* . .
* 1 3 7 5
*/
val BinaryTree = BinTreeNode(BinTreeNode(BinTreeLeaf(1), BinTreeLeaf(3)), BinTreeNode(BinTreeLeaf(7), BinTreeLeaf(5)))
leafSum(BinaryTree) should be(16)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment