尾递归 - Scala(任何其他语言)

尾递归 - Scala(任何其他语言)

问题描述:

我有一个关于尾递归的问题.据我所知,尾递归是函数的最后一次递归调用将传递函数的结果.但是当我有这样的功能时

i have a question about Tail recursion. As i know Tail recursion is when the last recursive call from function will deliver the result of the function. But when i have a function like this

def func1(n: Int): Int = {
   if (n > 100) {
      n - 10
   }
   else {
      func1(func1(n + 11))
   }
}

会是尾递归吗?例如

func1(100) = func1(func1(111)) = func1(101) = 91

所以最后一个递归调用将是 func1(101) 并且它应该传递结果以便尾递归对吗?我有点困惑.谢谢!

so the last recursive call would be func1(101) and it should deliver the results so that would be tail recursion right? I'm a little confused. Thank you!

任何简单的检查方法都是尝试一下.如果您的方法不是尾递归的,@tailrec 注释 (import scala.annotation.tailrec) 会给您一个编译时错误.

Any easy way to check would be to just try it. the @tailrec annotation (import scala.annotation.tailrec) will give you a compile-time error if your method is not tail recursive.

这不是尾递归,因为您在非尾位置有一个递归调用.

This is not tail recursive though because you have a recursive call in a non-tail position.

您的函数中有两个递归调用,一个在尾部位置,它是方法中的最后一个调用,但另一个是该调用的输入,它不是尾部递归,因为它后面有一些东西,下一个电话.尾部位置只有一次递归调用是不够的,每次递归调用都必须是尾调用

You have two recursive calls in your function, one is in a tail position, it's the last call in the method, but the other is the input to that call, which isn't tail recursive because something comes after it, the next call. It's not enough to have one recursive call in the tail position, every recursive call must be a tail call