Skip to content

Instantly share code, notes, and snippets.

@akimboyko
Last active December 29, 2015 04:38
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 akimboyko/7615819 to your computer and use it in GitHub Desktop.
Save akimboyko/7615819 to your computer and use it in GitHub Desktop.
How to acheive tail call optimization while traversing tree-like structure using continuation-passing style http://stackoverflow.com/q/20164061/443366
import util.control.TailCalls._
sealed abstract class Tree
case class Leaf(n: Int) extends Tree
case class Node(left: Tree, right: Tree) extends Tree
lazy val numbers = Seq.range(1, 20)
lazy val imbalancedTree = numbers.map(Leaf).foldLeft[Tree](Leaf(0))(Node)
def traverseTree(tree: Tree)(action: Int => Unit): Unit = {
def traverseTreeRec(tree: Tree, continuation: () => TailRec[Unit]): TailRec[Unit] = tree match {
case Leaf(n) => {
action(n)
continuation()
}
case Node(n1, n2) =>
tailcall(traverseTreeRec(n1,
() => traverseTreeRec(n2,
() => tailcall(continuation()))))
}
traverseTreeRec(tree, () => done(())).result
}
traverseTree(imbalancedTree)((n: Int) => println(n))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment