liveBook · Manning

Repeatedly

As explained in Clojure: The Essential Reference

repeatedly is a Clojure function that produces a lazy sequence by invoking a zero-argument function repeatedly, either a specified number of times or indefinitely.

repeatedly builds a lazy sequence by calling a zero-argument function for each element. With one argument, it continues indefinitely; with a repetition count, it stops after that many calls. section 9.2 section 9.2.1

The contract has two arities and several practical boundaries:

  • Use (repeatedly f) for an infinite lazy sequence, or (repeatedly n f) for a finite sequence. section 9.2.1
  • Supply a no-argument function; side effects or changing results make repeatedly useful, while a pure constant function generally repeats one value. section 9.2.1
  • Treat n as zero or a positive number; double values round upward, and nil f or n raises NullPointerException. section 9.2.1
  • Prefer repeat for a single repeating value and dotimes when only side effects matter and no result sequence is needed. section 9.2.1

Generate random values

(take 3 (repeatedly rand)) ;; (0.2416205627046507 0.8326807316362209 0.9275189497929626) (repeatedly 3 #(if (> (rand) 0.5) true false)) ;; (true false true)

Construct data and workers

Use repeatedly with gensym to create keys, or with future to build a lazy pool of concurrent workers. Consume an infinite sequence deliberately: taking too much data can exhaust memory.

Listing 9.6. → Function application, Sequence generation
(repeatedly
  ([f])
  ([n f]))

Inspect the two supported function signatures side by side. section 9.2.1

How Clojure: The Essential Reference covers it

How deep it goes
Defines both arities, laziness, input contract, exceptions, alternatives, and memory risks, while showing implementation with lazy-seq and cons.
Examples
Demonstrates random numbers, random booleans, generated keywords, concurrent workers, and an excessive realization causing memory failure.
What it assumes
Assumes familiarity with zero-argument functions, sequences, laziness, and basic Clojure function application.
What you can do after
Apply it to build finite or infinite lazy sequences from functions that produce changing values or side effects.
How it connects
Contrasts with repeat, dotimes, and iterate, and connects sequence generation with laziness, side effects, futures, and random data.

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.