sicp.io
2.4.3 · Data-directed programming and additivity

A package extends the table instead of editing every caller.

Install representation-specific constructors and selectors under operation and type keys, then add a new package without changing the generic dispatcher.

Guiding question

How can a generic system gain another representation or operation without reopening one central conditional?

  • Store procedures under explicit operation and type keys
  • Separate package installation from later generic application
  • Give representation-specific methods only untagged contents
  • Add a second representation without changing apply-generic
  • Observe additivity as table growth with stable client code

Each installer owns the details of one representation and registers four methods. apply-generic knows only how to read a type tag, retrieve a method, and pass it the contents. Rectangular contents store x before y; swapped contents store y before x. Both packages satisfy the same real-part, imag-part, magnitude-squared, and constructor protocol.

The second program begins with only an integer description method. A rational value initially produces no-method. Installing one more table entry makes the same describe dispatcher accept it without editing the dispatcher or the integer package. Additivity here is explicit and finite: extension occurs by registering another method under a new key.

SICP code2,221 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 package program returns (4 8 rectangular swapped 3 4 25 3 4 25). The additive extension program returns ((integer 7) no-method (fraction 3 2) 2).

    Trace focus

    Separate installation-time put calls from later get and method applications. Confirm that apply-generic is unchanged when swapped is installed. In the second program, compare the rational lookup before and after one new table entry appears.

    Try it yourself

    Change the program and compare the result.

    Add a translated representation whose contents store x plus 10 and y plus 10. Install selectors that subtract the translation and confirm the existing generic client still observes 3, 4, and 25.

    Show hint

    Keep the translation entirely inside the new constructor and methods; do not add a type branch to apply-generic.

    Complete this lesson

    0 of 20 lessons complete in this chapter0%