liveBook · Manning

Ensure-reduced

As explained in Clojure: The Essential Reference

ensure-reduced is a Clojure function that returns a value as a Reduced object without wrapping it again when it is already reduced.

ensure-reduced returns its argument as a Reduced object, wrapping an ordinary value but preserving a value that is already reduced. This makes reduced signaling composable when reducers or transducers may receive either form. section 7.3

Use it alongside the related Reduced controls:

  • reduced always wraps its argument; ensure-reduced avoids a second wrapper. section 7.3
  • reduced? tests whether a value is reduced, while unreduced or deref retrieves its contained value. section 7.3
  • A Reduced value signals reduce to stop processing remaining input, enabling premature termination. section 7.3

Preserving an existing signal

Given an already reduced value r, (ensure-reduced r) keeps r reduced rather than wrapping it again. Given an ordinary value such as "done", (ensure-reduced "done") produces a Reduced value whose contents can be inspected with @. section 7.3

How Clojure: The Essential Reference covers it

How deep it goes
Defines the input and output contract, contrasts related functions, and notes dereferencing and ClassCastException concerns.
Examples
Uses early-stopping reduction and a moving-average reducer to demonstrate Reduced values flowing through computation.
What it assumes
Assumes familiarity with reduce and Reduced values while defining the four related functions and dereferencing behavior.
What you can do after
Apply it to normalize reduction results while preserving existing early-termination signals.
How it connects
Connects reduced, reduced?, unreduced, reduce, reducers, and transducers through the Reduced signaling mechanism.

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.