1.31 Exercise 1.31
We can define a product procedure very similarly to the first sum procedure:
(define (product term a next b) | (if (> a b) | 1 | (* (term a) | (product term (next a) next b)))) |
|
We can use this procedure to define factorial as follows:
(define (factorial n) | (product identity 1 inc n)) |
|
We can use this procedure to compute pi as follows:
(define (pi-product n) | (define (numer n) | (define (numer-term i) | (if (divides? 2 i) | (+ i 2) | (+ i 1))) | (product numer-term 1 inc n)) | (define (denom n) | (define (denom-term i) | (if (divides? 2 i) | (+ i 1) | (+ i 2))) | (product denom-term 1 inc n)) | (* 4 (/ (numer n) (denom n)))) |
|
A product procedure computing an iterative process is as follows:
(define (product term a next b) | (define (iter a result) | (if (> a b) | result | (iter (next a) | (* result (term a))))) | (iter a 1)) |
|