Chapter 1, Building Abstractions with Procedures

Section - Formulating Abstractions with Higher-Order Procedures

Exercise 1.32


Accumulator by Recursive process:

1
2
3
4
5
6
7
8
9
10
(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)
     )
  )
)

Sum and Product:

1
2
3
4
5
6
7
8
  
(define (sum term a next b)
  (accumulate + 0 term a next b)
)

(define (product term a next b)
  (accumulate * 1 term a next b)
)

Accumulator by Iterative process:

1
2
3
4
5
6
7
8
(define (accumulate 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)
)