(define (product term a next b) (if (> a b) 1 (* (term a) (product term (next a) next b))))
factorial function, in terms of product function above, can be written as below.
(define (identity x) x) (define (next x) (+ x 1)) (define (factorial n) (product identity 1 next n))
approximations to pi using john wallis' formula, can be found by defining a new term to be used by product function as below
(define (pi-term n) (if (even? n) (/ (+ n 2) (+ n 1)) (/ (+ n 1) (+ n 2))))
And it can be used as follows.
(* (product pi-term 1 next 6) 4) ;;= 3.3436734693877552 (* (product pi-term 1 next 100) 4) ;;= 3.1570301764551676
(define (product term a next b) (define (iter a res) (if (> a b) res (iter (next a) (* (term a) res)))) (iter a 1))
<< Previous exercise (1.30) | sicp-solutions | Next exercise (1.32) >>