如何创建一个尾递归方法,它也可以以非尾递归方式引用自身

时间:2013-03-11 09:04:45

标签: scala recursion tail-recursion

假设我有一个长时间运行的计算机制,可以暂停自己以便以后恢复:

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))

如何在非暂停调用中保留尾递归?

1 个答案:

答案 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)
}