Scala 是否支持尾递归优化? [英] Does Scala support tail recursion optimization?

查看:54
本文介绍了Scala 是否支持尾递归优化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala 是否支持尾递归优化?

Does Scala support tail recursion optimization?

推荐答案

Scala 在编译时进行尾递归优化,正如其他发布者所说.即尾递归函数被编译器转化为循环(方法调用转化为跳转),从运行尾递归函数时的堆栈轨迹可以看出.

Scala does tail recursion optimisation at compile-time, as other posters have said. That is, a tail recursive function is transformed into a loop by the compiler (a method invoke is transformed into a jump), as can be seen from the stack trace when running a tail recursive function.

试试下面的代码片段:

def boom(n: Int): Nothing = if(n<=0) throw new Exception else boom(n-1)
boom(10)

并检查堆栈跟踪.它只会显示对函数 bom 的一次调用——因此编译后的字节码不是递归的.

and inspect the stack trace. It will show only one call to the function boom - therefore the compiled bytecode is not recursive.

有一个提议在 JVM 级别实现尾调用 - 其中在我看来,这将是一件很棒的事情,因为 JVM 可以进行运行时优化,而不仅仅是代码的编译时优化 - 并且可能意味着更灵活的尾递归.基本上,tailcall invoke 的行为与普通方法 invoke 完全一样,但会在安全的情况下丢弃调用者的堆栈 - JVM 的规范指出堆栈帧必须保留,因此 JIT 必须进行一些静态代码分析,以确定是否永远不会使用堆栈帧.

There is a proposal floating around to implement tail calls at the JVM level - which in my opinion would a great thing to do, as then the JVM could do runtime optimizations, rather than just compile time optimizations of the code - and could possibly mean more flexible tail recursion. Basically a tailcall invoke would behave exactly like a normal method invoke but will drop the stack of the caller when it's safe to do so - the specification of the JVM states that stack frames must be preserved, so the JIT has to do some static code analysis to find out if the stack frames are never going to be used.

它的当前状态是 proto 80%.我不认为它会在 Java 7 中及时完成(invokedynamic 具有更高的优先级,并且实现几乎完成)但 Java 8 可能会看到它实现.

The current status of it is proto 80%. I don't think it will be done in time for Java 7 (invokedynamic has a greater priority, and the implementation is almost done) but Java 8 might see it implemented.

这篇关于Scala 是否支持尾递归优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆