Clojure - Recursion


Advertisements


We have seen the recur statement in an earlier topic and whereas the ‘for’ loop is somewhat like a loop, recur is a real loop in Clojure.

If you have a programming background, you may have heard of tail recursion, which is a major feature of functional languages. This recur special form is the one that implements tail recursion. As the word “tail recursion” indicates, recur must be called in the tail position. In other words, recur must be the last thing to be evaluated.

The simplest example of the recur statement is used within the ‘for’ loop. In the following example, the recur statement is used to change the value of the variable ‘i’ and feed the value of the variable back to the loop expression.

Example

Live Demo
(ns clojure.examples.hello
   (:gen-class))

;; This program displays Hello World
(defn Example []
   (loop [i 0]
      (when (< i 5)
      (println i)
      (recur (inc i)))))
(Example)

Output

The above program produces the following output.

0
1
2
3
4


Advertisements