Exercise 1.31.
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 formula52

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.


(define (inc n) (+ n 1))
(define (identity x) x)
(define
(prod-iter-helper
runningsum
operation
termfunction
termvalue
nextfunction
upperbound)
(if
(> termvalue upperbound)
runningsum
(prod-iter-helper
(operation runningsum (termfunction termvalue))
operation
termfunction
(nextfunction termvalue)
nextfunction
upperbound)))
(define (product term starter a next b)
(prod-iter-helper
starter
*
term
a
next
b))
(define (product-integers a b)
(product identity 1 a inc b))
(define (factorial b)
(product identity 1 1 inc b))
(define (even? n)
(= (remainder n 2) 0))
(define (pi-term index)
(if
(even? index)
(/ (+ index 2) (+ index 1))
(/ (+ index 1) (+ index 2))))
(define (pi-approx n)
(* 4.0 (product pi-term 1/1 1/1 inc (/ n 1))))

view raw

s131.scm

hosted with ❤ by GitHub

Discover more from Gaurav Sharma's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading