(Lispex)sicp.io
2.1 · Abstraction barriers

Build with an interface, not a representation.

Constructors and selectors let a program use rational numbers without spreading knowledge of their pair representation through every operation.

Guiding question

What does an abstraction barrier protect us from changing?

  • Separate an abstract value from its representation
  • Use constructors and selectors as the only boundary
  • Recognize code that reaches through an abstraction

make-rat constructs a rational value. numer and denom select its parts. add-rat depends on those three operations, not on car, cdr, or the order in which the pair stores its fields.

The pair is useful machinery, but it is not the public idea. Keeping representation knowledge behind a small interface makes later changes local instead of contagious.

Lispex · SICP sourceScheme-compatible SICP syntax executed by the Lispex SICP profile.
(begin
  (define (make-rat n d) (cons n d))
  (define (numer x) (car x))
  (define (denom x) (cdr x))
  (define (add-rat x y)
    (make-rat (+ (* (numer x) (denom y))
                 (* (numer y) (denom x)))
              (* (denom x) (denom y))))
  (let ((answer (add-rat (make-rat 1 2) (make-rat 1 3))))
    (/ (numer answer) (denom answer))))
Lispex learning runtimeLispex SICP profile 1.0.0
Loading Lispex SICP runtime
Lispex · SICP source346 / 1,048,576 UTF-8 bytes
Examples
Result
Output
Value
Diagnostic
Visible execution0 / 0 trace events
    This browser result is not a Lispex Vouch record or authority.wasm —
    Expected observation

    The first program returns the exact rational value 5/6.

    Trace focus

    Follow calls to make-rat, numer, and denom. add-rat never needs a direct pair operation, so its process does not reveal the storage order.

    Try it yourself

    Change the program before you read the hint.

    Store the denominator first in make-rat. Change only numer and denom, then confirm that add-rat still returns 5/6.

    Show one hint

    If add-rat must change, some representation knowledge crossed the intended boundary.