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.
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.
- Output
- —
- Value
- —
- Diagnostic
- —
The first program returns (5.0 5.0). The second returns (13.0 13.0).
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.
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.