I try to implement tail call optimization to traverse tree-line structure using continuation-passing style in scala. Unfortunately my previous experience with fsharp does not help much. I have recursive call w/o tail optimization:
def traverseTree(tree: Tree)(action: Int => Unit): Unit = {
def traverseTreeRec(tree: Tree, continuation: () => Unit, action: Int => Unit): Unit = tree match {
case Leaf(n) => {
action(n)
continuation()
}
case Node(n1, n2) => {
traverseTreeRec(n1, () => traverseTreeRec(n2, continuation, action), action)
}
}
traverseTreeRec(tree, () => (), action)
}
Afterwards I try to rewrite using @annotation.tailrec
and TailCalls
, but still not sure how to decorate continuation
def traverseTree(tree: Tree)(action: Int => Unit): Unit = {
@annotation.tailrec
def traverseTreeRec(tree: Tree, continuation: () => TailRec[Unit], action: Int => Unit): TailRec[Unit] = tree match {
case Leaf(n) => {
action(n)
continuation()
}
case Node(n1, n2) =>
// how to properly implement tail call here?
// ERROR: it contains a recursive call not in tail position
traverseTreeRec(n1, () => tailcall(traverseTreeRec(n2, continuation, action)), action)
}
traverseTreeRec(tree, () => done(), action)
}
Thanks in advance