liveBook · Manning

Repeat

As explained in Clojure: The Essential Reference

repeat is a Clojure function that produces a lazy sequence containing repeated copies of a value, either indefinitely or a specified number of times.

repeat generates a lazy sequence containing repeated copies of one value. With one argument it repeats indefinitely; with a count it limits the result. section 9.2.3

Its contract is small but includes useful edge cases:

  • x is mandatory and may be any expression or value, including nil. section 9.2.3
  • n is optional; zero or a negative value produces an empty PersistentList, while a double is truncated to an integer. section 9.2.3
  • A nil n raises NullPointerException; the result is a sequence-compatible clojure.lang.Repeat object. section 9.2.3

Repeat values for sequential processing

(defn bang [sentence] (map str (.split #"\\s+" sentence) (repeat "!"))) (bang "Add exclamation each word") ;; ("Add!" "exclamation!" "each!" "word!") (repeat 5 1) ;; (1 1 1 1 1)

(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))

The recursive repeat* sketch makes infinite lazy generation concrete through cons and lazy-seq. section 9.2

How Clojure: The Essential Reference covers it

How deep it goes
Defines arities, laziness, output types, edge cases, and a cons/lazy-seq implementation sketch.
Examples
Demonstrates mapped punctuation, finite ones, exponentiation with reduce, tally marks, and lazy prefixes with take.
What you can do after
Apply it via map, reduce, concat, and take to build repeated-input transformations and bounded sequences.
How it connects
Contrasts repeat with cycle, repeatedly, iterate, map, reduce, and concat as sequence-generation or processing tools.

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.