Exercise 1.32

Read Exercise 1.32 ~ Solution


a) accumulate, sum-acc, product-acc

(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))))

(define (sum-acc a b)
  (accumulate + 0 identity a inc b))

(define (product-acc a b)
  (accumulate * 1 identity a inc b))

b) accumulate-iter

(define (accumulate-iter 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))

Leave a comment