Closures and Shared Mutable State

A closure captures lexical cells, not frozen value copies, so related procedures can coordinate through one private binding.

At a glance

LISPEX
(define counter (let ((n 0)) (lambda () (set! n (+ n 1)) n)))
(list (counter) (counter))

Result

OUTPUT
(1 2)

Working method

  • Create the state in an enclosing let, return procedures that read or mutate it, and keep the cell unreachable except through those procedures.
  • Shadowed bindings allocate different cells; set! updates the nearest resolved binding.
  • Top-level redefinition updates the original global cell seen by earlier closures.

Boundaries

  • Shared mutation is deterministic here, but it still deserves narrow ownership and explicit tests.