Skip to content

Instantly share code, notes, and snippets.

@alkagin
Created November 3, 2014 19:11
Show Gist options
  • Save alkagin/eac3b131afca15b7ff6c to your computer and use it in GitHub Desktop.
Save alkagin/eac3b131afca15b7ff6c to your computer and use it in GitHub Desktop.
Example of tail recursion in scala
sealed abstract class Tree
case class Leaf(x: Int) extends Tree
case class Node(a: Tree, b: Tree) extends Tree
def sumTree(t: Tree): Int = {
def sumTreeHelper(trees: List[Tree], acc: Int): Int = trees match {
case Nil => acc
case Leaf(x) :: result => sumTreeHelper(result, x + acc)
case Node(a, b) :: result => sumTreeHelper(a :: b :: result, acc)
}
sumTreeHelper(List(t), 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment