Clojure-snips: Tail recursion in Clojure

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 +
            #(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.


One thought on “Clojure-snips: Tail recursion in Clojure

  1. Pingback: Writing about Clojure | ansh bansal

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s