(Lispex)sicp.io
1.4 · 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.

Lispex · SICP sourceScheme-compatible SICP syntax executed by the Lispex SICP profile.
(begin
  (define (sum term a next b)
    (if (> a b)
        0
        (+ (term a) (sum term (next a) next b))))
  (define (identity x) x)
  (define (inc x) (+ x 1))
  (sum identity 1 inc 10))
Lispex learning runtimeLispex SICP profile 1.0.0
Loading Lispex SICP runtime
Lispex · SICP source192 / 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 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 before you read the hint.

    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 one hint

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