Closures(v1 · en)

Concept

A closure = a function value + a captured lexical environment. An fn remembers, at its definition site, the bindings it can see; wherever the function value travels afterwards, it still reads those same binding cells — not same-named ones at the call site. What is captured is the binding, not a copy of the value. That is precisely the contrast with an ordinary function: an ordinary function's output is determined by its input alone, while a closure's behavior also depends on the captured environment.

(defun make-adder [k] (fn [x] (+ x k)))
(println ((make-adder 4) 3))

Expected stdout:

7

When (make-adder 4) returns, the parameter binding k should be gone; the closure keeps it alive. Captured bindings are mutable: set! updates the captured cell, and the closure thereby gains memory.

(defun make-counter []
  (let [n 0]
    (fn [] (set! n (+ n 1)) n)))
(def c (make-counter))
(println (c))
(println (c))
(def d (make-counter))
(println (d))
(println (c))

Expected stdout:

1
2
1
3

c and d each captured the n from a different call, so they do not interfere: when c has counted to 2, d starts at 1, and c continues with 3. Sharing versus isolation depends on which call performed the capture — see Shared State.

Design notes

Closures are lexical scope cashed out at runtime: bind time (the definition site) decides which binding cell a name reads; call time only supplies the arguments. Making closures capture bindings rather than copy values gives the language a first-class form of state for free — counters, caches and private ledgers need no object syntax. The price is lifetime: a captured binding cannot be reclaimed while any closure holding it lives, so the implementation must give captured environments storage (environment frames). Zio splits "several closures sharing one binding cell" into its own explicit topic because it is the root of isolation questions: whoever holds the same cell shares the same mutable history.

Going further

The Scheme lambda paper (Sussman and Steele, "Scheme: An Interpreter for Extended Lambda Calculus") established closures as first-class citizens: the Mae West principle — "when I go somewhere, I go along" — the environment travels with the function. JavaScript's var-in-a-loop trap and Python's late-binding closure pitfall are accident reports from misreading "captures the binding, not the value". Zio's choice matches Scheme: capture bindings, keep behavior predictable; for isolation, call the factory again. The experiment Closure sharing and isolation runs both paths side by side.

前序概念

后续概念