22 hours ago

my attempt to do the exercises in sicp.

## Sunday, June 29, 2008

### sicp exercise 1.31

; 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 pie using the formula

;

; pi/4 = 2/3.4/3.4/5.6/5.6/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.

(define (prod-recur term a next b)

(if (> a b)

1

(* (term a)

(prod-recur term (next a) next b))))

(define (prod-iter term a next b)

(define (prod-iter-impl term a next b res)

(if (> a b)

res

(prod-iter-impl term (next a) next b (* (term a) res))))

(prod-iter-impl term a next b 1))

(define (fact n)

(define (next x) (+ x 1))

(define (term x) x)

(prod-iter term 1 next n))

;(display (fact 500)) (newline)

(define (pi)

(define (next x) (+ x 1))

(define (term x)

(cond ((even? x) (/ x (+ x 1)))

(else (/ (+ x 1) x))))

(* (prod-iter term 2 next 1000) 4))

(display (rationalize (pi) 0.000001)) (newline)

Subscribe to:
Post Comments (Atom)

## No comments:

Post a Comment