1.32 Exercise 1.32
A general accumulate procedure can be written as follows:
| (define (accumulate combiner null-value term a next b) | | (if (> a b) | | null-value | | (combiner (term a) | | (accumulate combiner null-value term (next a) next b)))) |
|
We can write sum and product using accumulate:
| (define (sum term a next b) | | (accumulate + 0 term a next b)) |
|
| (define (product term a next b) | | (accumulate * 1 term a next b)) |
|
We can write an iterative accumulate like this:
| (define (accumulate combiner null-value term a next b) | | (define (iter a result) | | (if (> a b) result | | (iter (next a) (combiner result (term a))))) | | (iter a null-value)) |
|