Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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));
  }
}
like image 933
IttayD Avatar asked Nov 09 '09 06:11

IttayD


1 Answers

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)  
  }
}
like image 178
Walter Chang Avatar answered Sep 21 '22 09:09

Walter Chang