4 ms·
> I'm also working on a cross-language compiler and have a question about TCO, specifically tail recursion. Currently my language compiles a tail-recursed funct
by prog 16y ago
> I'm also working on a cross-language compiler and have a question about TCO, specifically tail recursion. Currently my language compiles a tail-recursed function's body into a while loop. Don't Scala and Clojure do the same, except using the actual bytecode?
I know Scala does it at function level (i.e. the function calls itself at tail position). I think Clojure have a 'recur' keyword to similar effect. The issue with JVM is that if f() calls g() at tail position and g() calls f() at tail position, it can't be optimized away (at least not without an undue amount of work so the advantage is lost). Clojure uses a trampoline[1] based approach to handle such a situation. I think Scala 2.8 also adds support for that. This works well with constant space, the only issue is that its a performance hit as its not done by the VM.
[1] http://richhickey.github.com/clojure/clojure.core-api.html#clojure.core/trampoline http://richhickey.github.com/clojure/clojure.core-api.html#c...
- dfox 16y agocompiling self-recursive function into loop catches many cases of tail recursion but certainly not all. Real TCO requires some support from VM to be efficient (if you don't care about efficiency it is possible to fake it with exceptions).