sicp.io
2.5.1 · Generic arithmetic operations

Raise for a shared method, then drop only when information survives.

Build an integer, rational, and complex tower with explicit raising, same-type addition, equality, projection, and conservative result simplification.

Guiding question

How can mixed arithmetic find a common type and later return to a simpler type without discarding information?

  • Assign an explicit rank to every type in a numeric tower
  • Raise lower values until both operands share a method
  • Keep same-type arithmetic separate from coercion policy
  • Project a result only when raising it again reproduces the original value
  • Preserve a complex value when a nonzero imaginary component would be lost

add first raises the lower-ranked operand until both values share a tag. same-type-add then performs only representation-specific arithmetic. Integers raise to rationals with denominator 1; rationals raise to complex values with a zero imaginary rational. The arithmetic methods do not decide which conversions are allowed.

drop attempts the reverse direction conservatively. A rational projects to an integer only when its denominator is 1. A complex value projects to its real component only when its imaginary component is exactly zero. The projected value is raised again and compared with the original before simplification continues, so a nonzero imaginary component cannot disappear.

SICP code3,793 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 program returns ((rational 7 2) (integer 1) (integer 5) (complex (rational 3 1) (rational 1 1))).

    Trace focus

    For each add call, record both initial ranks and every raise. Then enter exactly one same-type method. Follow project, raise, and generic-equal? during dropping; the zero-imaginary complex result reaches integer 5, while the final nonzero-imaginary result remains complex.

    Try it yourself

    Change the program and compare the result.

    Add generic multiplication for the same three types and reuse the existing raising and dropping path. Test a rational product that becomes an integer and a complex product whose imaginary component remains nonzero.

    Show hint

    Keep conversion outside the same-type method. A complex product needs rational addition, subtraction, and multiplication for its two components.

    Complete this lesson

    0 of 20 lessons complete in this chapter0%