Created
November 3, 2014 19:11
-
-
Save alkagin/eac3b131afca15b7ff6c to your computer and use it in GitHub Desktop.
Example of tail recursion in scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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