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

3

8

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));
  }
}
Mckelvey answered 9/11, 2009 at 6:24 Comment(1)
note that JVM-level tailcall optimisation is contributed for java 7 see wikis.sun.com/display/mlvm/TailCallsPreliminaries
G
12

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)  
  }
}
Gompers answered 9/11, 2009 at 6:39 Comment(2)
+1 What's the rationale? ( I mean I can imagine it , but I would like to know )Cockloft
@OscarRyz: see #4786002Aquinas
R
1

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.

Radcliffe answered 9/11, 2009 at 11:17 Comment(0)
F
0

Inner functions are also eligible for TCO.

Ferity answered 9/11, 2009 at 14:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.