sicp.io
3.1.2 · The benefits of introducing assignment

A private location can turn a protocol into a reusable object.

Use assignment to keep instrumentation and experiment progress behind stable procedure interfaces instead of threading bookkeeping through every caller.

Guiding question

When does hidden state simplify the collaboration between otherwise independent procedures?

  • Encapsulate a call counter behind one monitored procedure
  • Separate ordinary requests from count and reset messages
  • Let a finite experiment remember which outcome comes next
  • Keep Monte Carlo control independent from experiment storage
  • State the reproducibility boundary of an explicit finite schedule

make-monitored adds one private calls binding to an arbitrary procedure. Ordinary numeric messages increment the binding and delegate to the wrapped procedure. The count and reset messages inspect or change instrumentation without requiring every caller to carry a count value alongside the real argument.

The second program separates a Monte Carlo controller from a stateful experiment object. monte-carlo knows only that calling experiment produces the next boolean result. The supplied finite list makes this run reproducible and directly models the modular benefit of assignment.

SICP code552 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 monitoring program returns (9 16 2 reset 0). The finite experiment returns ((3 5 3/5) exhausted).

    Trace focus

    Locate the private calls binding and distinguish ordinary delegation from count and reset messages. In the experiment, follow the cdr assignment after each outcome and verify that monte-carlo never inspects the outcome list directly.

    Try it yourself

    Change the program and compare the result.

    Extend make-monitored with a last-result message, then construct two experiments from the same outcome list and interleave them. Predict which private locations can affect one another.

    Show hint

    Each constructor call creates its own locations. The controller should continue to use only the experiment procedure interface.

    Complete this lesson

    0 of 21 lessons complete in this chapter0%