Data can be the behavior promised by an interface.
Represent pairs and points as procedures, then recover their components only through selector messages rather than stored pair positions.
If constructors and selectors satisfy the same contract, must an abstract data value have one particular physical representation?
- Treat a constructor-selector contract as the meaning of an abstract datum
- Represent a pair with a procedure that receives a selector procedure
- Recover nested procedural-pair components without direct car or cdr storage
- Use message dispatch as another procedural representation
- Keep client code independent from the representation technique
cons-proc does not allocate a conventional pair for its two components. It returns a procedure that remembers x and y and later gives both values to a selector. car-proc and cdr-proc supply selectors that choose one component. Nested values still work because the contract, not a printed storage shape, defines the pair operations.
The point example uses message dispatch. make-point returns a procedure that answers x, y, and sum messages. The selectors know only those messages. A conventional pair, a vector, or another closure could replace this implementation if the same observable constructor-selector behavior remains available.
- Output
- —
- Value
- —
- Diagnostic
- —
The procedural-pair program returns (left right 1 2 3). The message-passing point returns (3 4 7 unknown-message).
Separate constructor calls that create closures from selector calls that later invoke them. In the nested pair, follow the cdr-proc result as another procedural pair. In the point example, locate one captured x and y environment serving several messages.
Change the program and compare the result.
Add a swap message to make-point that returns a new procedural point with x and y reversed. Use only x-point and y-point to inspect the result.
Show hint
The new point can be created by calling make-point inside the dispatch procedure; clients still need no representation access.