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

