假设我有一个长时间运行的计算机制,可以暂停自己以便以后恢复:
sealed trait LongRunning[+R];
case class Result[+R](result: R) extends LongRunning[R];
case class Suspend[+R](cont: () => LongRunning[R]) extends LongRunning[R];
如何运行它们的最简单方法是
@annotation.tailrec
def repeat[R](body: LongRunning[R]): R =
body match {
case Result(r) => r
case Suspend(c) => {
// perhaps do some other processing here
println("Continuing suspended computation");
repeat(c());
}
}
问题在于创建这样的计算。假设我们想要实现尾递归因子,它每10个周期暂停一次计算:
@annotation.tailrec
def factorial(n: Int, acc: BigInt): LongRunning[BigInt] = {
if (n <= 1)
Result(acc);
else if (n % 10 == 0)
Suspend(() => factorial(n - 1, acc * n))
else
factorial(n - 1, acc * n)
}
但是这不能编译:
错误:无法优化
@tailrec
带注释的方法factorial
:它包含不在尾部位置的递归调用Suspend(() => factorial(n - 1, acc * n))
如何在非暂停调用中保留尾递归?
答案 0 :(得分:4)
我找到了一个可能的答案。我们可以将tail-recursive部分移动到内部函数中,并在需要时引用外部函数,非尾递归部分:
def factorial(n: Int, acc: BigInt): LongRunning[BigInt] = {
@annotation.tailrec
def f(n: Int, acc: BigInt): LongRunning[BigInt] =
if (n <= 1)
Result(acc);
else if (n % 10 == 0)
Suspend(() => factorial(n - 1, acc * n))
else
f(n - 1, acc * n)
f(n, acc)
}