I recently came across recur in Clojure. It is a special form which allows for tail recursion in Clojure. If you have worked with Java you would know that JVM does not have tail recursion implemented due to all those stackoverflows that we face when using Java.
I had this code for summing the digits of a number repeatedly till I get a single digit which I wanted to improve so I asked for a code review
(defn sum-once [x] (reduce + (map #(Integer/parseInt (str %)) (seq (char-array x))))) (defn sum-digits [x] (let [y (sum-once x)] (if (< y 10) y (recur (str y)))))
I came to know about recur. Simply said we just replace the call of sum-digits inside sum-digits with recur and that’s it. Now instead of stacks Clojure does something else and we get optimized tail recursion which Java does not have.
It works with functions and loop. The loop docs is full of recur and that’s the only way to use loop.
To use recur we simply use it like a function call (like everything else in Clojure) with the exactly same number of arguments as the function or loop in which it is called.