Scala 中是否可以保证尾递归优化?
假设我有以下代码
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。要确定,请将
@tailrec
注释添加到您的方法中。如果不使用尾递归进行编译,这将导致编译器抛出错误。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.否,
Unit
返回类型不相关。但是:
您需要将递归调用作为最后一次调用,返回类型并不重要。
您问题中的代码很好,但问题的标题可能会产生误导。
No, the
Unit
return type is irrelevant.But:
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.