Why can't scalac optimize tail recursion in certain scenarios?

送分小仙女□ 提交于 2019-12-12 08:35:08

问题


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));
  }
}

回答1:


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)  
  }
}



回答2:


Try this:

class Foo {
  def ifak(n: Int, acc: Int):Int = {
    if (n == 1) acc
    else ifak(n-1, n*acc)
  }
}

class Bar extends Foo {
  override def ifak(n: Int, acc: Int): Int = {
    println("Bar!")
    super.ifak(n, acc)
  }
}

val foobar = new Bar
foobar.ifak(5, 1)

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.




回答3:


Inner functions are also eligible for TCO.



来源:https://stackoverflow.com/questions/1699376/why-cant-scalac-optimize-tail-recursion-in-certain-scenarios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!