← back to programming

Mutable Data

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

set-car! and set-cdr! turn pairs into mutable building blocks. Queues, tables, and circuits built from mutation. But sharing creates identity puzzles: eq? vs equal?.

before 1 2 car cdr set-car! after 1 99 2 car cdr mutation changes the pair in place — all references see the change

Mutable list structure

set-car! and set-cdr! mutate the two halves of a pair in place. With these primitives, lists become mutable data structures.

Scheme

Representing queues

A queue needs O(1) insertion at the rear. The trick: maintain a pointer to both the front and rear of the list. set-cdr! on the rear pair threads in new elements.

Scheme

Representing tables

A table is an association list with a header. Lookup scans the list; insert either updates an existing entry or prepends a new one. Two-dimensional tables nest a table inside each entry.

Scheme

A simulator for digital circuits

Wires carry signals; gates transform them. Each wire maintains a list of action procedures that fire when its signal changes. This is event-driven simulation built from mutation and closures.

Scheme

Notation reference

Scheme Python Meaning
(set-car! p v)p[0] = vMutate first element of pair
(set-cdr! p v)p[1:] = vMutate rest of pair
(eq? a b)a is bSame object in memory
(equal? a b)a == bStructurally equal
(assoc key alist)dict.get(key)Lookup in association list / dict

Translation notes

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