a. The sum procedure is only the simplest of a vast number of similar abstractions that can be captured as higher-order procedures.51 Write an analogous procedure called product that returns the product of the values of a function at points over a given range. Show how to define factorial in terms of product. Also use product to compute approximations to using the pi / 4 = (2/3) * (4/3) * (4/5) * (6/5) * (6/7) * (8/7) ...
b. If your product procedure generates a recursive process, write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.
I wrote the following:
(define (product term a next b) (cond ((> a b) 1) (else (* (term a) (product term (next a) next b)))))
(define (i-product term a next b) (cond ((> a b) null) (else (define (iter a result) (cond ((> a b) result) (else (iter (next a) (* (term a) result))))) (iter a 1))))
Multiply-integers [test - does (product ...) work?]
(define (identity x) x) (define (inc x) (+ 1 x)) (define (multiply-integers a b) (i-product identity a inc b))
(define (square x) (* x x)) (define (compute-pi steps) (define (next n) (+ n 2.0)) (* 8.0 (* steps 2) (/ (i-product square 4.0 next (* (- steps 1) 2)) (i-product square 3.0 next (* steps 2)))))
(define (factorial n) (define (next n) (+ n 1)) (i-product identity 1 next n))
What do you think of my solution?