Recursion in Clojure

1 minute read

Just want to make a note so that I don’t forget. I am reading Clojure to build very complex, concurrent systems that deal with lot of data. Using OOPS for that is a pain, it collapses when we hit about 0.2 million lines of code. I had done recursion in Clojure and this is how it works:

;; recursion.clj

(defn print-array [array]
  (let [first-element (first array)
        rest-elements (rest array)]
    (if first-element
      (do
        (println first-element)
        (print-array rest-elements)))))

(print-array [1 2 3 4])

In the program above we are printing an array element by element. The function we wrote for that is called print-array, note how at the end we are calling the same function from that function like this: (print-array rest-elements). Well, this is all good, but the book Getting Clojure says this will slow up the computer if you have lot of elements, instead it tells us to use recur as shown below:

;; recursion-2.clj

(defn print-array [array]
  (let [first-element (first array)
        rest-elements (rest array)]
    (if first-element
      (do
        (println first-element)
        (recur rest-elements)))))

(print-array [1 2 3 4])

This recur should be the last line of a function and so it is in the case above. As an OOP guy I find that bit disturbing that recur should be in the last line, but I found OOP disturbing while learning it being a C programmer. Some how this will prevent the computer from slowing down!

Updated: