Hacker News new | ask | show | jobs
by moondowner 4827 days ago
Maybe someone who knows Scala or Clojure internals can answer this question..
3 comments

scala doesn't optimize general tail calls, either (only direct tail recursion of final methods). If you want to optimize tail calls on the JVM, you must use trampolining, which adds some overhead to every call. So most languages choose fast calls without tail call elimination over slower calls with tail call elimination (i.e., speed over correctness).
Support for tail calls pretty much depends on the actual runtime implementation.

If it is important to you (it certainly is to me), use an implementation which supports proper tail calls.

I'm doing it and I have never looked back.

Out of curiosity, which implementation are you using?
This is very cool. Thank you!
Someone has made TCO possible in Clojure already: https://github.com/cjfrisz/clojure-tco
That's very cool. But note that as far as I can tell it only handles mutual recursion, not arbitrary tail calls (e.g. calls to a function argument).
Clojure has a loop/recur construct which makes the tail recursion explicit so doesn't need to be done by the JVM. In other words regular recursive calls should not be used for loops if you want performance.
Scala has a similar explicit @Tailrec annotation for its compiler, too:

"A method annotation which verifies that the method will be compiled with tail call optimization. If it is present, the compiler will issue an error if the method cannot be optimized into a loop."

http://www.scala-lang.org/api/current/index.html#scala.annot...

I think rail recursion can be handled automatically by the compiler without any support from the jvm (scala does it).

The issue is different for general tail call elimination.