Scala 中是否可以保证尾递归优化?

发布于 2024-12-16 21:35:43 字数 166 浏览 2 评论 0原文

假设我有以下代码

def foo(x:Int):Unit = {
   if (x == 1) println ("done")
   else foo(scala.util.Random.nextInt(10))
}

是否保证编译器进行尾递归优化?

Suppose I have following code

def foo(x:Int):Unit = {
   if (x == 1) println ("done")
   else foo(scala.util.Random.nextInt(10))
}

Is it guaranteed that the compiler does tail recursion optimization?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

煮茶煮酒煮时光 2024-12-23 21:35:43

是的。要确定,请将 @tailrec 注释添加到您的方法中。如果不使用尾递归进行编译,这将导致编译器抛出错误。

@tailrec
def foo(x:Int):Unit = {
  if (x == 1) println ("done")
  else foo(scala.util.Random.nextInt(10))
}

Yes. To know for sure add the @tailrec annotation to your method. This will cause the compiler to throw an error if it does not compile using tail recursion.

@tailrec
def foo(x:Int):Unit = {
  if (x == 1) println ("done")
  else foo(scala.util.Random.nextInt(10))
}
掩耳倾听 2024-12-23 21:35:43

Unit 返回类型不相关。

scala> @tailrec def f(i: Int) { if (i >= 0) { println(i); f(i - 1) }  }
f: (i: Int)Unit

但是:

scala> @tailrec def f(i: Int) { if (i >= 0) { f(i - 1); println(".") }  }
<console>:11: error: could not optimize @tailrec annotated method f:
  it contains a recursive call not in tail position

您需要将递归调用作为最后一次调用,返回类型并不重要。

您问题中的代码很好,但问题的标题可能会产生误导。

No, the Unit return type is irrelevant.

scala> @tailrec def f(i: Int) { if (i >= 0) { println(i); f(i - 1) }  }
f: (i: Int)Unit

But:

scala> @tailrec def f(i: Int) { if (i >= 0) { f(i - 1); println(".") }  }
<console>:11: error: could not optimize @tailrec annotated method f:
  it contains a recursive call not in tail position

You need to have the recursive call as the last call, return type does not matter.

Your code in the question is fine but the title of the question would be misleading.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文