liveBook · Manning

Closure

As explained in Clojure: The Essential Reference

A closure is a function that retains references to bindings from its defining lexical environment.

A closure is a function that retains references to bindings from its defining lexical environment. In Clojure, fn* exposes a specialized way to create closure objects for computations known to run only once, allowing captured references to be cleared after the result returns. section 2.1.3

The once-only form differs from an ordinary fn in several practical ways:

  • fn* underlies the fn macro but supports fewer features, including no pre- and post-conditions or destructuring. section 2.1.3
  • A normal lambda may remain reachable for later executions, while fn* can clear references held by a once-only function after it returns. section 2.1.3
  • The ^:once metadata form gives the compiler a special compile-time meaning that ordinary fn does not support. section 2.1.3

Delegating a macro to a once-only closure

A common pattern wraps an unevaluated macro body in an anonymous once-only function: (defmacro future [& body] `(future-call (^{:once true} fn* [] ~@body))). This lets the macro delegate execution to a function while avoiding unnecessary retention of captured data. section 2.1.3

How Clojure: The Essential Reference covers it

How deep it goes
Explains closure lifetime, captured-reference clearing, compiler metadata, and feature differences, but defers ordinary fn usage to its separate contract.
Examples
Demonstrates fn* syntax and a future macro using ^:once metadata with future-call.
What it assumes
Assumes familiarity with Clojure functions and macros, while distinguishing fn* from the more featureful fn form.
What you can do after
Evaluate closure lifetime and memory-retention tradeoffs, and recognize once-only function objects in macro implementations.
How it connects
Connects closures with lexical environments, lambdas, macros, futures, delays, and the fn special form.

Also explained in

Compare how 20 books explain closure →

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.