Exercise 1.32. a. Show that sum and product (exercise 1.31) are both special cases of a still more general notion called accumulate that combines a collection of terms, using some general accumulation function:

(accumulate combiner null-value term a next b)

Accumulate takes as arguments the same term and range specifications as sum and product, together with a combiner procedure (of two arguments) that specifies how the current term is to be combined with the accumulation of the preceding terms and a null-value that specifies what base value to use when the terms run out. Write accumulate and show how sum and product can both be defined as simple calls to accumulate.

b. If your 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.


(define (inc n) (+ n 1))
(define (identity x) x)
(define
(sum-iter-helper
runningsum
operation
termfunction
termvalue
nextfunction
upperbound)
(if
(> termvalue upperbound)
runningsum
(sum-iter-helper
(operation runningsum (termfunction termvalue))
operation
termfunction
(nextfunction termvalue)
nextfunction
upperbound)))
(define (sum term starter operation a next b)
(sum-iter-helper
starter
operation
term
a
next
b))
(define (accumulate combiner null-value term a next b)
(sum term null-value combiner a next b))
(define (sum-integers a b)
(accumulate + 0 identity a inc b))
(sum-integers 1 10)
(define (factorial b)
(sum identity 1 * 1 inc b))
(sum-integers 1 8)

view raw

s132.scm

hosted with ❤ by GitHub

Discover more from Gaurav Sharma's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading