假设我有一种用于长时间运行的计算的机制,它可以暂停自己以便稍后恢复:
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))
如何在非挂起调用上保留尾递归?