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
