sicp.io
5.3.1 · Memory as vectors

A pair can be an address into parallel car and cdr vectors.

Allocate fixed-capacity pair cells in two vectors, represent references as explicit pointers, and observe list order, mutation, and shared tails.

Guiding question

How can car, cdr, mutation, and sharing survive when a pair is represented by an integer address rather than a host pair?

  • Represent a pair pointer separately from an atomic datum
  • Allocate matching slots in parallel car and cdr vectors
  • Implement car, cdr, set-car!, and set-cdr! through pointer indexes
  • Construct and decode a finite list in vector memory
  • Observe two allocated pairs sharing one represented tail
  • Keep capacity exhaustion visible rather than assuming infinite memory

The memory object contains two equal-length vectors and one free index. A represented pair is (ptr index). memory-car and memory-cdr use that index in the parallel vectors; allocation writes both fields and advances free. list->memory builds the tail first, so the root of (a b c) is the last of three allocated cells even though decoding restores the source order.

The sharing example allocates one tail and stores its pointer in two different outer cells. Changing the tail car through that one pointer changes both decoded lists. This is the same graph question as host-pair sharing, but the identity is now an explicit address. The fixed vector capacity and monotonically advancing free pointer remain visible limitations until a storage manager reclaims or copies live cells.

SICP code2,879 of 1,048,576 UTF-8 bytes
Examples
Result
Output
Value
Diagnostic
Execution trace0 / 0 events
    Programs run in the browser with their result and execution trace.
    Expected result

    The list allocation returns (3 (ptr 2) (a b c) a b c (c b a) (() (ptr 0) (ptr 1))). The sharing run returns (3 (left changed) (right changed) #t 0).

    Trace focus

    Follow the free pointer and note that c, b, and a occupy indexes 0, 1, and 2 because tail construction finishes first. In the sharing run, verify that the two outer cdr slots contain the same (ptr 0) value and that only one car-vector slot changes.

    Try it yourself

    Change the program and compare the result.

    Implement a destructive vector-memory append that changes only the final represented cdr slot. Then create a cycle and write a decoder with a visit budget that reports revisited pointer indexes.

    Show hint

    The final cell is the pointer whose represented cdr is the empty list. A cycle-safe traversal must remember pointer indexes before following either field.

    Complete this lesson

    0 of 23 lessons complete in this chapter0%