Pass the part that changes.
A higher-order procedure captures the common shape of a computation while accepting the varying operation as an argument.
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.
(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))- Output
- —
- Value
- —
- Diagnostic
- —
The first program returns 55. The second returns 55 as well.
Notice that term and next are looked up and applied on every step. The procedure values travel through the same evaluator as numeric values.
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.