Exercise 1.32

  • Recursive:
    (define (accumulate combine id term a next b)
      (if (> a b)
          id
          (combine (term a)
                   (accumulate combine id term (next a) next b))))
  • Iterative:

scheme (define (accumulate combine id term a next b) (define (iter a acc) (if (> a b) acc (iter (next a) (combine (term a) acc)))) (iter a id))

Implementing sum and product in terms of 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))

(sum identity 1 inc 10) => 55
(product identity 1 inc 10) => 3628800