为什么scalac在某些场景下无法优化尾递归?
为什么 scalac(Scala 编译器)不优化尾递归?
演示这一点的代码和编译器调用:
> cat foo.scala class Foo { def ifak(n: Int, acc: Int):Int = { if (n == 1) acc else ifak(n-1, n*acc) } } > scalac foo.scala > jd-gui Foo.class import scala.ScalaObject; public class Foo implements ScalaObject { public int ifak(int n, int acc) { return ((n == 1) ? acc : ifak(n - 1, n * acc)); } }
Why doesn't scalac (the Scala compiler) optimize tail recursion?
Code and compiler invocations that demonstrates this:
> cat foo.scala class Foo { def ifak(n: Int, acc: Int):Int = { if (n == 1) acc else ifak(n-1, n*acc) } } > scalac foo.scala > jd-gui Foo.class import scala.ScalaObject; public class Foo implements ScalaObject { public int ifak(int n, int acc) { return ((n == 1) ? acc : ifak(n - 1, n * acc)); } }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以重写的方法不能是尾递归的。试试这个:
Methods that can be overridden can NOT be tail recursive. Try this:
试试这个:
注意
ifak
可能是递归的,但也可能不是递归的。将类或方法标记为final,它可能会成为尾递归。Try this:
Notice that
ifak
may be recursive, but it may not as well. Mark the class or the method final, and it shall probably made tail-recursive.内部函数也符合 TCO 条件。
Inner functions are also eligible for TCO.