我尝试使用scala中的连续传递样式实现尾调用优化以遍历树线结构。不幸的是,我以前使用fsharp的经验并没有多大帮助。我有没有尾优化的递归调用:
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)
}
之后我尝试使用@annotation.tailrec
and重写TailCalls
,但仍然不确定如何装饰延续
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)
}
提前致谢
ps:关于要点的完整示例