本文介绍了为什么scalac在某些场景下不能优化尾递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么 scalac(Scala 编译器)优化尾递归?
证明这一点的代码和编译器调用:
> 猫 foo.scala类 Foo {def ifak(n: Int, acc: Int):Int = {如果(n == 1)acc否则 ifak(n-1, n*acc)}}> scalac foo.scala> jd-gui Foo.class导入 scala.ScalaObject;公开课 Foo实现 ScalaObject{公共 int ifak(int n, int acc){返回 ((n == 1) ? acc :ifak(n - 1, n * acc));}} 解决方案
可以被覆盖的方法不能是尾递归的.试试这个:
class Foo {private def ifak(n: Int, acc: Int): Int = {如果(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)); } }
解决方案
Methods that can be overridden can NOT be tail recursive. Try this:
class Foo {
private def ifak(n: Int, acc: Int): Int = {
if (n == 1) acc
else ifak(n-1, n*acc)
}
}
这篇关于为什么scalac在某些场景下不能优化尾递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!