liveBook · Manning

Side effect

As explained in Clojure: The Essential Reference

A side effect is an observable interaction or state change produced by evaluating a computation in addition to returning a value.

A side effect is an observable action or state change that occurs while a computation runs, apart from the value it returns. Printing, advancing a stream’s read position, and updating a transient collection are examples. Clojure favors value-producing transformations, but provides iteration forms for work whose purpose is an effect. section 3.4.4 section 3.4.5 section 20.5

Choose an iteration form according to whether you need results. `dotimes` executes a body a fixed number of times and always returns `nil`; a count of zero or less skips the body. `repeatedly` instead builds a lazy sequence from calls to a no-argument function. Its calls can produce different values or launch work, but occur as the sequence is consumed. section 3.4.5 section 9.2.1

Effects versus collected values

`(dotimes [i 3] (println i))` prints `0`, `1`, and `2`, then returns `nil`. By contrast, `(take 3 (repeatedly rand))` yields three random values. Use `dotimes` when there are no results to collect; use `repeatedly` when the generated values matter. section 3.4.5 section 9.2.1

`while` is useful when each test must observe changing conditions. Reading from a Java stream, for example, advances its position; successive tests can therefore detect the end of the stream. For ordinary iteration, prefer approaches that do not require effects to make progress, such as sequence transformations. section 3.4.4

How Clojure: The Essential Reference covers it

How deep it goes
Explains concrete effects through iteration contracts, return behavior, stream reads, and lazy sequence consumption.
Examples
Uses console printing, file-stream hashing, transient-vector updates, random values, and futures as concrete cases.
What it assumes
Assumes familiarity with Clojure expressions and functions while defining the relevant iteration and sequence-generation contracts.
What you can do after
Apply it via `dotimes` for effect-only repetition or `repeatedly` when successive calls should supply sequence values.
How it connects
Connects side effects to `while`, `dotimes`, `repeatedly`, lazy sequences, Java IO, and transient collections.

Also explained in

Compare how 24 books explain side effect →

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.