sicp.io
2.5.3 · Generic symbolic algebra

A polynomial package turns algebra into operations on tagged data.

Sparse term lists keep powers and coefficients explicit, while generic add and multiply merge equal orders and preserve the polynomial variable.

Guiding question

How can a generic arithmetic system manipulate polynomial structure without scattering term-list details through client code?

  • Represent a sparse polynomial as a variable plus descending terms
  • Merge equal powers while adding two term lists
  • Distribute one term across a polynomial during multiplication
  • Remove zero-coefficient terms at the representation boundary
  • Dispatch polynomial add and multiply through type-tagged methods
  • Reject operations whose polynomial variables do not match

The first program represents each term as an order and coefficient and stores terms from highest order to lowest. add-terms performs the same ordered merge used earlier for sets: the larger order is copied, equal orders are combined, and adjoin-term omits a zero result. The polynomial package owns that representation and exposes one tagged add method. Adding x² + 2x + 1 to x² − 1 therefore produces 2x² + 2x without leaving an explicit zero constant term. A y polynomial returns different-variables instead of silently combining unrelated indeterminates.

The second program multiplies one term by every term in the other polynomial, shifts orders by addition, multiplies coefficients, and merges the partial products through add-terms. Multiplying x + 1 by x − 1 creates two middle terms that cancel, leaving x² − 1. A separate evaluator uses the package selectors and reports 8 at x = 3. This lesson models sparse univariate integer-coefficient polynomials with tagged addition, multiplication, normalization, and evaluation.

SICP code2,685 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 addition program returns ((polynomial x (2 2) (1 2)) different-variables). The multiplication program returns ((polynomial x (2 1) (0 -1)) 8).

    Trace focus

    In addition, follow the descending-order comparison and locate the equal-order coefficient sum that drops the zero constant term. In multiplication, follow each order shift, coefficient product, recursive partial product, and add-terms merge that cancels the two order-1 terms. The variable check happens before either representation operation proceeds.

    Try it yourself

    Change the program and compare the result.

    Multiply x² + x + 1 by x − 1, predict the sparse term list, and evaluate the result at x = 2.

    Show hint

    Generate one partial product for each left term, then merge equal orders. The order-1 and order-0 cancellations happen at different stages.

    Complete this lesson

    0 of 20 lessons complete in this chapter0%