liveBook · Manning

Pure function

As explained in Clojure: The Essential Reference

A pure function produces the same result for the same arguments and has no observable side effects.

A pure function produces the same result for the same arguments and has no observable side effects. This predictable contract makes function results safe to reuse, reason about, and memoize. section 2.4.2 section 20.5

Purity matters because it changes how functions can be used:

  • Memoization can return a previously stored result when the same arguments recur, provided no outside context changes the answer. section 2.4.2
  • A pure function passed to repeatedly would generate the same item repeatedly; use repeat when that is the intended behavior. section 9.2.1
  • Functions treated as values can be wrapped transparently, making purity useful alongside higher-order functions. section 2.4.2

Memoizing a predictable function

A Levenshtein-distance function is wrapped with memoize. The first call for a pair computes and stores the result; a later call with the same pair reuses it. The example reports 400 cache hits after repeating the same search, while returning the same best matches.

Listing 2.25. → Caching, Function Wrapper, Function Generation, Performance
(memoize [f])

Inspect the compact memoize signature as a direct entry point for applying purity to cached function results. section 2.4.2

How Clojure: The Essential Reference covers it

How deep it goes
Defines repeatable results and absent observable effects, then explains referential transparency without descending into implementation internals.
Examples
Uses memoized Levenshtein distance and contrasts predictable pure output with repeatedly-generated random values and side-effecting workers.
What it assumes
Assumes functions accept arguments and can be treated as values, while clarifying referential transparency through memoization.
What you can do after
Apply memoize safely when function results depend only on arguments and recognize when repeated calls require fresh effects.
How it connects
Connects pure functions to memoization, referential transparency, higher-order functions, lazy sequences, and side effects.

Also explained in

Compare how 19 books explain pure function →

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.