爲什麼scalac(Scala編譯器)不優化尾遞歸?爲什麼在某些情況下scalac不能優化尾遞歸?
代碼和編譯器調用演示了此:
> 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)); } }
請注意,JVM級別的tailcall優化是爲java 7貢獻的,請參閱http://wikis.sun.com/display/mlvm/TailCalls – 2009-11-09 11:25:52