Solution to SICP Exercise 1.29

Structure and Interpretation of Computer Programs

Solution to Exercise 1.29:

(define (sum term a next b)
(if (> a b)
0
(+ (term a)
(sum term (next a) next b))))

(define (inc n) (+ n 1))

(define (simpsons-integral f a b n)
(define (do-it h)
(define (y k)
(f (+ a (* k h))))
(define (simpson-term k)
(* (y k)
(cond ((or (= k 0) (= k n)) 1)
((odd? k) 4)
(else 2))))
(* (/ h 3) (sum simpson-term 0 inc n)))
(do-it (/ (- b a) n)))

Advertisements