liveBook · Manning

Cycle

As explained in Clojure: The Essential Reference

cycle is a Clojure function that repeatedly traverses input items in order to produce an unbounded lazy sequence.

cycle takes a collection and lazily produces an unbounded sequence by repeating its items in their original order. Use take or another bounded consumer when only a finite prefix is needed. section 9.2 section 9.2.3

Key behavior:

  • Accepts a sequential collection or nil; an empty input produces an empty persistent list. section 9.2.3
  • Returns a sequence-compatible clojure.lang.Cycle object that repeats indefinitely. section 9.2.3
  • Differs from repeat: repeat duplicates one value, while cycle traverses multiple input values in order. section 9.2

Bound an infinite cycle

(take 5 (cycle [1 2 3])) ;; (1 2 3 1 2) A short collection can therefore supply a longer sequential view, such as alternating signs, recurring traffic-light states, or repeated symbols. section 9.2.3

(take 5 (repeat (+ 1 1))) ; #1
;; (2 2 2 2 2)

(take 5 (cycle [1 2 3])) ; #2
;; (1 2 3 1 2)

Compare finite observation of repeat and cycle directly through executable examples. section 9.2.3

How Clojure: The Essential Reference covers it

How deep it goes
Defines inputs, outputs, laziness, empty-input behavior, and implementation strategy without detailing the Java internals.
Examples
Demonstrates bounded cycling, alternating values, traffic-light states, repeated alphabets, and performance-oriented reduction.
What it assumes
Assumes familiarity with sequential collections, lazy sequences, and bounded consumers such as take.
What you can do after
Apply it via Clojure's cycle function to adapt finite collections into unbounded lazy sequences.
How it connects
Connects cycle with lazy sequences, repeat, map, concat, trampoline, random sampling, reduction, and transducers.

Also explained in

Compare how 2 books explain cycle →

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.