liveBook · Manning

Recursion

As explained in Clojure: The Essential Reference

Recursion is a computation technique in which a function invokes itself, directly or through other functions, on a successive subproblem or state.

Recursion replaces mutation-driven iteration with successive calls that pass changing values as arguments. In Clojure, loop and fn forms provide recursion targets, while recur transfers execution to the next iteration. section 3.4

A recursive loop has three essential parts:

  • Pass each successive state—such as a counter and result collection—as arguments to the next invocation. section 3.4.4
  • Use an exit condition, commonly if or cond, to decide when the computation returns its final value. section 3.4
  • Recognize tail recursion when the recursive call is the last instruction in its scope; Clojure uses recur for this loop-style transfer. section 3.4
  • Prefer recursion or sequence operations over mutable while loops when expressing iteration in idiomatic functional Clojure. section 3.4.4

Collecting squares

(loop [i 0 s []] (if (< i 10) (recur (inc i) (conj s (* i i))) s)) ;; [0 1 4 9 16 25 36 49 64 81] The counter and collection become loop bindings. Each recur supplies their next values; when the condition fails, s is returned. section 3.4

(loop [i 0 s []]
  (if (< i 10)
    (recur (inc i) (conj s (* i i)))
    s))
;; [0 1 4 9 16 25 36 49 64 81]

View the complete loop-recur example with its executable result. section 3.4

How Clojure: The Essential Reference covers it

How deep it goes
Defines targets, exit conditions, and tail calls, then works through a loop-recur collection example.
Examples
Uses square collection and counter accumulation examples, alongside Java for and do-while contrasts.
What you can do after
Apply it via Clojure loop and recur to build iteration without mutating loop variables.
How it connects
Connects recursion to loop, recur, tail recursion, while, mutation, and list comprehension.

Also explained in

Compare how 23 books explain recursion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.