Learn/Clojure/5. Loops and recursion
Lesson 5 of 8
Sign in

Clojure, lesson 5

Loops and recursion

Clojure has no for (i = 0; i < n; i++) loop with a counter that changes, because values never change. Instead, you either walk over a sequence of values, or you recur: start the loop again with new values.

Ranges and doseq

(range start end) produces the numbers from start up to, but not including, end. An optional third argument is the step:

doseq runs its body once for each element of a sequence. It is the tool for printing and other side effects:

If the sequence is empty, the body never runs. When you simply need to repeat something n times, (dotimes [i n] ...) gives you from 0 to .

2 exercises to try what you just read.

Exercise 1

Countdown

Press Ctrl Enter or Check to test your code.

Exercise 2

Total until zero

Press Ctrl Enter or Check to test your code.

i
n - 1

loop and recur

When you need to compute something, or decide step by step when to stop, use loop with recur. loop sets up names with starting values, just like let. Inside it, (recur ...) jumps back to the top of the loop with new values for those names:

Read it as: "start with n = 1 and total = 0; if n is past 100, print the total, otherwise go round again with n + 1 and total + n". Every loop needs a branch that does not call recur; that is where it stops.

recur must be the last thing evaluated in its branch (its tail position), and it must give a new value for every loop name, in order. In return, it uses no extra memory, so a loop can run millions of times.

Recursion in functions

recur also works directly inside a function, where it restarts the function with new arguments:

Early exit

Stopping early is simply choosing not to recur. This loop reads lines until it sees stop and returns how many lines came before it:

Once the loop returns, no more input is read. That is Clojure's version of break.

In everyday Clojure you will often avoid explicit loops altogether by using sequence functions like map, filter and reduce. You'll meet them in the lesson on collections. loop/recur remains the tool when the next step depends on what you just saw, like reading until a marker.

Further reading

  • Learn Clojure: Flow Control (looping)
  • Special Forms: loop and recur

Read a whole number n (0 or more). Print the numbers from n down to 1, one per line, then print Liftoff!.

Sample input:

Sample output:

A cashier types prices, one per line, and types 0 when the order is complete. Read the prices and print the total of everything before the first 0. Anything after the 0 belongs to the next customer and must be ignored. There is always a 0 in the input.

Use loop and recur with a running total.

Sample input:

Sample output:

(range 1 4)        ; (1 2 3)
(range 5)          ; (0 1 2 3 4)
(range 10 0 -2)    ; (10 8 6 4 2)
(doseq [lap (range 1 4)]
  (println "Lap" lap))
(loop [n 1
       total 0]
  (if (> n 100)
    (println total)              ; 5050
    (recur (inc n) (+ total n))))
(defn countdown [n]
  (if (zero? n)
    (println "Go!")
    (do (println n)
        (recur (dec n)))))

(countdown 3)       ; 3, 2, 1, Go!
(loop [seen 0]
  (let [line (read-line)]
    (if (= line "stop")
      seen
      (recur (inc seen)))))
3
3
2
1
Liftoff!
12
5
8
0
25