liveBook · Manning

Mutation

As explained in Clojure: The Essential Reference

Mutation is the alteration of a value or variable's state after it has been established.

Mutation alters a value or variable’s state after it has been established. Imperative iteration commonly depends on mutation: a loop updates a counter so its termination test eventually succeeds. Clojure instead steers this changing state through recursion, sequence construction, and controlled side effects. section 3.4.4 section 20.5

Mutation appears here mainly as a contrast between imperative state changes and functional iteration:

  • Java’s do-while example increments a mutable count inside the loop body. section 3.4.4
  • Clojure passes the changing count as a recur argument, using loop-recur and a condition to control termination. section 3.4.4
  • List comprehensions assemble a sequence of values instead of repeatedly mutating the value checked by the loop. section 3.4.4
  • Clojure permits necessary side effects but regulates them and encourages applications toward functional purity. section 20.5

Replacing a mutable counter

An imperative loop prints counts 1 through 3 by incrementing count. The Clojure version carries that state explicitly: (loop [count 1] (when (< count 4) (println "Count is:" count) (recur (inc count)))). A second version accumulates [1 2 3] with conj, while map, for, and dorun provide sequence-oriented alternatives. section 3.4.4

(loop [count 1]
  (when (< count 4)
    (println "Count is:" count)
  (recur (inc count))))

;; Count is: 1
;; Count is: 2
;; Count is: 3
;; nil

Inspect the direct Clojure translation of a mutable Java counter loop, including explicit state progression and termination. section 3.4.4

How Clojure: The Essential Reference covers it

How deep it goes
Contrasts mutable counters with recur, list comprehension, and regulated side effects without developing a general mutation API.
Examples
Uses Java and Clojure counter loops, accumulated results, sequence iteration, and a stream-reading hash computation.
What you can do after
Evaluate/understand when Clojure replaces mutable loop state with recur, accumulated values, or sequence processing.
How it connects
Connects mutation with iteration, recursion, list comprehension, side effects, and functional purity.

Also explained in

Compare how 12 books explain mutation →

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.