Wednesday, June 3, 2009

Ex-1.32

;a
(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
(define (sum term a next b)
(accumulate + 0 term a next b))
;product
(define (product term a next b)
(accumulate * 1 term a next b))

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

Important thing to notice is that how we reached to accumulator, we wrote sum, product & identified a common pattern and abstracted it out in accumulate. Higher order procedure give more flexibility to apply this concept.

No comments:

Post a Comment