Last active
December 29, 2015 04:38
-
-
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
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
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