sicp.io
2.4.2 · Data-directed dispatch

A type tag chooses the representation-specific operation.

A generic interface can combine an operation name with a data type, then retrieve the matching procedure from one table instead of branching at every caller.

Guiding question

How does an operation table preserve one interface across different representations?

  • Attach an explicit type tag to representation contents
  • Use an operation and type pair as a dispatch key
  • Keep rectangular and polar magnitude formulas separate
  • Call one generic magnitude interface for both representations

Each table entry pairs the key (magnitude type) with a procedure that understands only that type’s contents. The rectangular procedure computes the square root of x squared plus y squared, while the polar procedure reads the stored radius.

apply-generic removes the tag only after get has selected the matching procedure. Client code names magnitude and supplies tagged data without asking which representation it contains. Adding a representation changes the table rather than the generic interface.

SICP code969 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 (5.0 5.0). The second returns (13.0 13.0).

    Trace focus

    Follow get comparing the operation and type key before apply-generic passes only contents to the selected procedure. The rectangular run reaches sqrt, while the polar run returns the first content field.

    Try it yourself

    Change the program and compare the result.

    Add a magnitude entry for a one-dimensional representation tagged linear, then call the unchanged apply-generic interface with a stored length of 9.0.

    Show hint

    The new key is (magnitude linear). Its procedure can return the first content field.

    Complete this lesson

    0 of 20 lessons complete in this chapter0%