sicp.io
1.3.1 · Procedures as arguments

Pass the part that changes.

A higher-order procedure captures the common shape of a computation while accepting the varying operation as an argument.

Guiding question

How can one procedure describe an entire family of sums?

  • Treat a procedure as an ordinary value
  • Identify the invariant structure in a summation
  • Supply behavior through term and next parameters

sum does not know whether it is adding integers, squares, or another sequence. term selects the value to add. next selects the following point. The recursion owns only the shared traversal pattern.

This separation is the beginning of a powerful design habit. Name the stable process once and pass in the decisions that vary.

SICP code192 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 first program returns 55. The second returns 55 as well.

    Trace focus

    Notice that term and next are looked up and applied on every step. The procedure values travel through the same evaluator as numeric values.

    Try it yourself

    Change the program and compare the result.

    Define a double procedure for term and a step-two procedure for next. Use sum to add the doubled odd numbers from 1 through 9.

    Show hint

    The traversal boundary stays the same even when next skips values.

    Complete this lesson

    0 of 18 lessons complete in this chapter0%