Exercise 1.32
a. Show that sum and product (Exercise 1.31) are both special cases of a still more general notion called a c c u m u l a t e accumulate accumulate that combines a collection of terms, using some general accumulation function:
(accumulate combiner null-value term a next b)
a c c u m u l a t e accumulate accumulate takes as arguments the same term and range specifications as s u m sum sum and p r o d u c t product product,together with a c o m b i n e r combiner combiner procedure (of two arguments) that specifies how the current term is to be combined with the accumulation of the preceding terms and a n u l l − v a l u e null-value null−value that specifies what base value to use when the terms run out. Write a c c u m u l a t e accumulate accumulate and show how s u m sum sum and p r o d u c t product product can both be defined as simple calls to a c c u m u l a t e accumulate accumulate.
b. If your a c c u m u l a t e accumulate accumulate procedure generates a recursive process, write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.
answer :
- a
; use recursive
(define (accumulate-recur combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a)
(accumulate-recur combiner null-value term (next a) next b))))
; computes the summation of two numbers
(define (sum a b)
(accumulate-recur + 0 identity a inc b))
; computers the production of two numbers
(define (product a b)
(accumulate-recur * 1 identity a inc b))
(sum 3 5)
(product 3 5)
- b
; use iter
(define (accumulate-iter combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (combiner (term a) result))))
(iter a null-value))
; computes the summation of two numbers
(define (sum a b)
(accumulate-iter + 0 identity a inc b))
; computers the production of two numbers
(define (product a b)
(accumulate-iter * 1 identity a inc b))
(sum 3 5)
(product 3 5)