5 ms·
This is why clojure has a special form for tail call where you can "recur" a loop by re-binding the variables. When proper tail call comes to JVM, it'll be poss
by sunkencity 17y ago
This is why clojure has a special form for tail call where you can "recur" a loop by re-binding the variables. When proper tail call comes to JVM, it'll be possible to do write the loop as a function call instead of hiding it inside a function.
(def factorial
(fn [n]
(loop [cnt n acc 1]
(if (zero? cnt)
acc
(recur (dec cnt) (* acc cnt))))))
- xtho 17y agoIn java, you could use the "while" keyword for that. Anyway, tail-calls aren't necessarily loops. If I'm not mistaken, tail-call optimisation for looping constructs only (which the poster a few levels above probably had in mind) wouldn't require a special byte code.
- tmountain 17y agoWith the added benefit that it will warn you if you're not really in tail position. The only place where recur falls flat is with mutual recursion in which case you need to use trampoline. I love me some Clojure.