liveBook · Manning

Iterate

As explained in Clojure: The Essential Reference

iterate is a Clojure function that returns an infinite lazy sequence formed by repeatedly applying a unary function to the preceding result.

iterate generates an infinite lazy sequence by repeatedly applying a unary function: the initial value appears first, followed by (f x), (f (f x)), and so on. section 9.2.2

Its contract is small and precise:

  • Takes a one-argument function f and an initial value x of any type. section 9.2.2
  • Produces lazily, so consumers such as take can request only the required prefix. section 9.2.2
  • Expects f to be free of side effects; nil f raises NullPointerException, while a non-function f raises ClassCastException. section 9.2.2

Simple progression and Fibonacci state

(take 10 (iterate inc 0)) ;; (0 1 2 3 4 5 6 7 8 9) (def fibo (iterate (fn [[x y]] [y (+' x y)]) [0 1])) (take 10 (map first fibo)) ;; (0 1 1 2 3 5 8 13 21 34) The state need not be numeric: each step can transform a structured value into the next state. section 9.2.2

Iterating evolving systems

A Game of Life simulation can use (iterate (partial next-gen height width) init) to produce successive grid states. The same pattern supports series calculations consumed by transduce. section 9.2.2

(defn repeatedly* [f] ; #1
  (lazy-seq (cons (f) (repeatedly* f))))

(defn iterate* [f x] ; #2
  (lazy-seq (cons x (iterate* f (f x)))))

(defn repeat* [x] ; #3
  (lazy-seq (cons x (repeat* x))))

(defn cycle* [coll] ; #4
  ((fn step [[x & xs]]
     (lazy-seq
       (if x
         (cons x (step xs))
         (cycle* coll)))) coll))

(defn range* [n] ; #5
  ((fn step [x]
     (lazy-seq
       (when (< x n)
         (cons x (step (inc x)))))) 0))

A compact recursive sketch makes the contract visible: emit x, then lazily recur with (f x). section 9.2

How Clojure: The Essential Reference covers it

How deep it goes
Defines inputs, outputs, laziness, side-effect expectations, exceptions, and recursive implementation behavior.
Examples
Demonstrates counting, Fibonacci generation, numerical series, and successive Game of Life states.
What it assumes
Assumes unary functions and sequence processing while illustrating lazy recursion from a simple implementation.
What you can do after
Apply it via Clojure sequence consumers to build finite views of infinite numeric or state-dependent processes.
How it connects
Connects lazy sequences with transducers, Fibonacci numbers, state transitions, and the Game of Life.

Also explained in

Compare how 2 books explain iterate →

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.