a. The sum procedure is only the simplest of a vast number of similar abstractions that can be captured as higher-order procedures. 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 formula:

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.

A)

 
; recursive
(define (product term a next b)
  (if (> a b)
      1
      (* (term a)
         (product term (next a) next b))))
(product id 1 inc 6)
 
; factorial
(define (factorial n) (product id 1 inc n))
(factorial 6)
 
; pi
(define (approximate-pi terms)
  (define (term n)
    (/ (if (even? n) (+ n 2) (+ n 3))
       (if (even? n) (+ n 3) (+ n 2))))
  (* 4 (product term 0 inc (- terms 1))))
 
(approximate-pi 10)  ; 524288/160083 = 3.275
(approximate-pi 100) ; 3.1570301764551676
 
 

B)

; iterative
(define (product term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a) (* result (term a)))))
  (iter a 1))
 
(product id 1 inc 6)
 
exercise_1.31.txt · Last modified: 2009/03/02 01:02 by 204.14.159.185
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki