Name each stage, then compose the flow.
Enumeration, filtering, mapping, and accumulation separate one data question into stages that can be understood and replaced independently.
How does a sequence pipeline turn nested recursion into named stages?
- Enumerate a finite input interval
- Select values with a predicate and transform them with a procedure
- Accumulate a sequence into one result
- Read intermediate sequence shapes before predicting the final value
enumerate-interval creates the source sequence. filter keeps only values accepted by odd?, and map replaces every retained value with its square. Each procedure owns one decision.
accumulate combines the transformed sequence with + and the initial value 0. The complete program still recurses, but its control is distributed across reusable stages instead of fused into one special-purpose procedure.
(begin
(define (enumerate-interval low high)
(if (> low high)
'()
(cons low (enumerate-interval (+ low 1) high))))
(define (filter predicate items)
(cond ((null? items) '())
((predicate (car items))
(cons (car items) (filter predicate (cdr items))))
(else (filter predicate (cdr items)))))
(define (map procedure items)
(if (null? items)
'()
(cons (procedure (car items))
(map procedure (cdr items)))))
(define (accumulate operation initial items)
(if (null? items)
initial
(operation (car items)
(accumulate operation initial (cdr items)))))
(define (square value) (* value value))
(accumulate + 0
(map square
(filter odd? (enumerate-interval 1 8)))))- Output
- —
- Value
- —
- Diagnostic
- —
The program returns 84 from 1² + 3² + 5² + 7².
Follow the interval list into filter, then compare the shorter odd list with the squared list consumed by accumulate. The final additions happen only after the stages have established those intermediate shapes.
Change the program before you read the hint.
Change odd? to even?, then use cons and '() instead of + and 0 in accumulate. Predict the resulting list and its order.
Show one hint
The final stage can receive any two-argument procedure and matching initial value.