Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 36 ยท Language Basics

Loops in Clojure: loop, recur, doseq, for and dotimes

Learn iteration in Clojure: loop and recur for tail recursion, doseq and dotimes for side effects, the for comprehension, while, and when to prefer map, filter and reduce instead.

Clojure has no for (i = 0; i < n; i++) loop, because loops that change a counter need mutable variables. Instead, you have three families of tools: higher-order functions such as map and reduce (covered later), loops built with loop and recur, and a few macros for looping over collections and side effects. This lesson shows each tool and when to use it.

loop and recur

loop creates a recursion point with initial bindings. Inside the body, recur jumps back to the loop with new values for those bindings, without growing the call stack:

CLOJURE
(loop [i 0
       total 0]
  (if (> i 4)
    total
    (recur (inc i) (+ total i))))
;; => 10    (0 + 1 + 2 + 3 + 4)

Read it as: "start with i = 0 and total = 0; if i is above 4, return total; otherwise repeat with a new i and total". Nothing is mutated; each iteration has fresh bindings.

The same pattern works inside a function, where recur returns to the function's start:

CLOJURE
(defn factorial [n]
  (loop [n n
         acc 1N]
    (if (<= n 1)
      acc
      (recur (dec n) (*' acc n)))))

(factorial 20)    ; 2432902008176640000N
JS Stand-in: the loop/recur pattern as a while loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Rules for recur

  • recur must be in tail position: the very last thing evaluated in the branch. You cannot add anything after it, such as (+ 1 (recur ...)).
  • It must pass exactly as many arguments as the loop has bindings (or as the function has parameters).
  • The compiler checks both rules, so mistakes show up immediately as errors such as "Can only recur from tail position".
  • The JVM does not do general tail-call optimisation, so plain recursion like (defn f [n] (f (dec n))) will eventually overflow the stack. Use recur for deep loops.
CLOJURE
;; Counts down; uses the function itself as the recursion point
(defn countdown [n]
  (when (pos? n)
    (println n)
    (recur (dec n))))

How loop and recur work

loop Starts with initial values.
Test Done? Return a result.
recur Jump back with new values.
No stack growth Safe for millions of steps.

recur must be the last expression.

1 / 2

doseq: loops for side effects

doseq runs its body once for each item of a collection. It is used for side effects such as printing and returns nil:

CLOJURE
(doseq [fruit ["apple" "pear" "plum"]]
  (println "I like" fruit))

It can take several bindings, which behave like nested loops (the last one varies fastest), and optional modifiers :when, :while and :let:

CLOJURE
(doseq [x [1 2 3]
        y [:a :b]]
  (println x y))        ; 1 :a, 1 :b, 2 :a, 2 :b, 3 :a, 3 :b

(doseq [n (range 10)
        :when (even? n)
        :let [sq (* n n)]]
  (println n "squared is" sq))

dotimes: repeat n times

CLOJURE
(dotimes [i 3]
  (println "round" i))     ; round 0, round 1, round 2

dotimes counts from 0 to n - 1. It also returns nil, so it is for effects only.

for: building a sequence

Despite the name, for is a list comprehension: it produces a lazy sequence of results, not side effects. It supports the same bindings and :when, :while, :let modifiers as doseq:

CLOJURE
(for [x (range 5)] (* x x))                ; (0 1 4 9 16)

(for [x (range 1 4)
      y [:a :b]]
  [x y])
;; => ([1 :a] [1 :b] [2 :a] [2 :b] [3 :a] [3 :b])

(for [x (range 20)
      :when (zero? (mod x 7))]
  x)                                       ; (0 7 14)

Use for when you want a new collection and doseq when you want to do something with each element. Because for is lazy, nothing runs until the result is consumed (see the laziness chapter later in this course).

JS Stand-in: for comprehension with two generators

Press Run (or Ctrl + Enter) to see the console output here.

No output.

while

while repeats while a condition stays truthy. Because values are immutable, it is only useful with mutable state such as an atom:

CLOJURE
(def n (atom 3))
(while (pos? @n)
  (println "n is" @n)
  (swap! n dec))

You will study atoms in the state chapter. Most Clojure code never needs while.

Prefer data-processing functions

Many things that would be loops in other languages are one-liners with sequence functions:

CLOJURE
(reduce + (range 5))                 ; 10    instead of the sum loop
(map #(* % %) (range 5))             ; (0 1 4 9 16)
(filter even? (range 10))            ; (0 2 4 6 8)
(apply max [3 9 4])                  ; 9
(count (filter odd? (range 100)))    ; 50

Reach for loop/recur when the next step depends on a complex state, for example when you walk through a structure with several accumulators, or when you need an early exit. Otherwise reduce, map, filter and for are shorter and clearer, and you will see them in Higher-Order Functions.

A good first instinct: if the loop builds a value from a collection, try reduce. If it prints or writes something, try doseq. If it needs complex state, use loop.

Common mistakes

  • Using doseq or dotimes and expecting a return value. Both return nil.
  • Writing (for ...) for side effects and seeing nothing happen: lazy sequences do not run until consumed. Use doseq instead.
  • Calling recur in a non-tail position or with the wrong number of arguments.
  • Forgetting *' or N literals and overflowing a Long in factorial-style loops.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (loop [i 0] (if (< i 3) (recur (inc i)) i)) return?

    The loop repeats while i is below 3; when i reaches 3 the else branch returns it.
  2. 2. Which rule must recur follow?

    recur has to be the last evaluated expression and match the loop or function arity.
  3. 3. Which form should you use to print each item of a collection?

    doseq is for side effects. for and map are lazy and may not run at all.
  4. 4. What does (for [x (range 10) :when (odd? x)] x) produce?

    The :when modifier keeps only the odd numbers.

Summary

  • loop and recur give constant-stack iteration; recur must be in tail position and match the arity.
  • doseq and dotimes are for side effects and return nil; for builds a lazy sequence.
  • :when, :while and :let modifiers refine for and doseq.
  • reduce, map and filter often replace explicit loops.

Next: Lists and Vectors