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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (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)))) | |