by rit · 13y ago · 0 comments
Scala is usually the language brought up as a counter argument here, but Scala has the same limitations as Clojure - the JVM can't do the TCO. Scala's compiler tries, with certain types of tail calls, to optimize via (I believe) a trampoline – it reduces those calls into a loop, so they are no longer a function call.
But, only certain types of calls (specifically, the last line of code in a recursive function must be a call to the hosting function) can be TCO in Scala. There is an annotation, scala.annotation.tailrec, which can be placed above a method you want to tail recurse.
@tailrec does not, however, "force" the compiler to do TCO – it simply forces compilation to fail if the method in question cannot be Tail Call Optimized. It's a developer hook for saying "I realize the compiler tries to do TCO where possible, but I require this method to be trampolined". If it can't be, you'll get a compilation error with details on why the TCO failed.
So @tailrec tells the compiler to compile this call to an unconditional jump.
And the x86, as a platform, does?
What, specifically, does the JVM do to make TCO more difficult than it would be in the machine code of your choice?
"It's complicated."
http://stackoverflow.com/questions/105834/does-the-jvm-preve...
OK, why do functions in the source language have to translate directly into methods at the JVM level? Purely for debugging?