0
\$\begingroup\$

Given this task:

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.

I wrote the following solution:

Recursive:

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

Iterative:

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

Sum/Product using iterative accumulate:

(define (sum term a next b) (i-accumulate + 0 term a next b))
(define (product term a next b) (i-accumulate * 1 term a next b))

What do you think?

\$\endgroup\$
1
\$\begingroup\$

Since the only parameter that changes in your recursive definition is a, you can write an inner definition like so:

(define (accumulate combiner null-value term a next b)
  (define (rec a)
    (if (> a b)
        null-value
        (combiner (term a) (rec (next a)))))
  (rec a))
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.