I'm having trouble finding the answer to this in the Clojure docs. I'm new to Clojure and it seems as though you can use recur
in two different ways and essentially get the same result.
Example 1:
(defn my-function [num]
(if (> num 10)
num
(recur (+ num 1))))
Example 2:
(defn my-function [num]
(loop [cnt num]
(if (> cnt 10)
cnt
(recur (+ cnt 1)))))
From what I can tell, these two forms seem to do the exact same thing. I understand that the reason recur
is good generally is that under the right circumstances the compiler can hack together some kind of pseudo-tail-call-optimization, which I really like and would love to make use of as often as possible. So here are my questions:
- What is the need for using
loop
whenrecur
seems to work without it? - Does
loop
just create a "recursion scope" kind of like howlet
creates a mini scope? - If so, can I still get the tail recursion benefits without using
loop
?
loop
you can accept (and pass) arbitrary set of parameters, withoutloop
you must pass only what function can accept. – Knickerbockersif
instead ofwhen
in both. I've taken the liberty of correcting them (I hope!), – Stringboardwhen
instead ofif
? – Birdiebirdlikewhen
does not use an else clause. It's essentially ado
block with a condition at the beginning. – Birdiebirdlikecnt
s have no side effect, hence are quite redundant in the middle of awhen
form. – Stringboard