← back to programming

Assignment & State

Abelson & Sussman ยท 1996 ยท SICP ยง3.1

set! introduces time into the model. Once variables can change, substitution breaks down. Objects with local state model real-world entities but sacrifice referential transparency.

100 75 35 -25 -40 tโ‚€ tโ‚ tโ‚‚ balance changes over time โ€” set! makes history matter

Local state variables

make-withdraw returns a procedure that remembers its balance. Each call to the returned procedure mutates the enclosed variable. The procedure has state.

Scheme

A full bank account bundles deposit and withdraw behind a message-passing interface:

Scheme

The costs of introducing assignment

Without set!, calling a procedure with the same arguments always returns the same result. That is referential transparency. Assignment destroys it: (W 25) returns different values on successive calls. The substitution model cannot explain this; we need the environment model (next chapter).

Scheme

The benefits of assignment: Monte Carlo

Assignment enables clean modular design when modeling processes with internal randomness. The Monte Carlo method estimates π by testing random points in the unit square. The random number generator hides its state; the estimator does not need to know how randomness works.

Scheme

Sameness and change

If two variables refer to the same mutable object, changing one affects the other. Before set!, "same" meant "equal value." After set!, we must distinguish identity (same object) from equality (same value).

Scheme

Notation reference

Scheme Python Meaning
(set! x v)x = vMutation โ€” assign new value
(begin e1 e2)e1; e2Sequencing โ€” evaluate in order
(lambda (x) body)lambda x: bodyClosure โ€” captures enclosing scope
(eq? a b)a is bIdentity โ€” same object
(equal? a b)a == bEquality โ€” same value

Translation notes

Neighbors
Ready for the real thing? Read SICP §3.1.