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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With