Shared State(v2 · en)

注:本概念在 v2 无独立正文,正文沿自 v1(未修订即沿用——显式标注而非静默回退)。

Concept

Shared state = several closures holding the same binding cell. State attaches not to objects or global variables but to bindings: whoever captured it at definition time can read and write it. Closures from one factory call share; closures from different calls are isolated. Isolation and sharing are two outcomes of the same capture rule, not two mechanisms.

(defun make-pair []
  (let [n 0]
    [(fn [] (set! n (+ n 1)) n)
     (fn [] n)]))
(def pair (make-pair))
(def tick (get pair 0))
(def peek (get pair 1))
(println (tick))
(println (tick))
(println (peek))
(def other (make-pair))
(def opeek (get other 1))
(println (opeek))
(println (peek))

Expected stdout:

1
2
2
0
2

tick and peek came from the same (make-pair) and read/write the same n: after the two increments, peek sees 2. other is a second call whose own n starts at 0; the original pair's peek still reports 2. Writing "an account with a private ledger" needs no object system — one let and two fn forms.

Design notes

Hanging state on closures rather than mutable globals gives two safety properties. First, closed by default: if no closure escapes, nobody can reach the binding — the state's very existence is private. Second, sharing must be explicit: making two functions share a cell requires letting them be born from the same capture. This is the reverse of object systems, where any reference holder can touch a field and encapsulation rests on discipline. Capability languages apply "the reference is the capability" to closures: returning a closure = returning a capability — see Modules and Capability Boundaries.

Going further

SICP chapter 3 introduces local state through a balance counter: state is necessary for modeling and a source of trouble, because the same expression now yields different values at different times and referential transparency is lost. The functional camp (Haskell) pushes state into types; the Lisp camp keeps assignment but demands explicit boundaries. Zio's position: the capture rule already defines the minimal unit of sharing (one binding cell); boundaries across sessions and modules belong to modules and authorization. The experiment Closure sharing and isolation lays the "shared" and "isolated" observations side by side on the same code.

前序概念

后续概念