sicp.io
3.2.3 · Closures and locations

Each closure can own a private location.

Two procedures made by the same constructor can execute the same code while remembering different bindings.

Guiding question

Why do two counters made by one procedure not overwrite each other?

  • Connect a closure to the environment where it was created
  • Separate equal procedure code from distinct stored locations
  • Predict observations from shared and private bindings

Each call to make-counter creates a new value binding and returns a procedure that keeps access to it. left and right share the lambda expression, but they do not share that binding.

The second example moves value outside both procedures. That single location is then shared, so an update through either procedure becomes the starting point for the other.

SICP code246 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 first program returns (1 2 11 3 12).

    Trace focus

    Compare the two make-counter applications with the later calls to left and right. The repeated lambda body reaches the location captured by its own creation environment.

    Try it yourself

    Change the program and compare the result.

    Create a third counter starting at 100. Interleave all three counters and predict which calls can affect one another.

    Show hint

    Count calls to make-counter. Each call creates one new private value binding.

    Complete this lesson

    0 of 21 lessons complete in this chapter0%