Blob


1 ;; Exercise 1.30. The sum procedure above generates a linear recursion. The procedure can be rewritten so that the sum is performed iteratively. Show how to do this by filling in the missing expressions in the following definition:
3 (define (product term a next b)
4 (if (> a b)
5 1
6 (* (term a)
7 (product term (next a) next b))))
9 (define (product-iter term a next b)
10 (define (iter i result)
11 (if (> i b)
12 result
13 (iter (next i) (* (term i) result))))
14 (iter a 1))
16 (define (factorial n)
17 (product (lambda (x) x)
18 1
19 (lambda (x) (+ x 1))
20 n))
22 (define (factorial-iter n)
23 (product-iter (lambda (x) x)
24 1
25 (lambda (x) (+ x 1))
26 n))
28 ;; pi/4 = 2*4*4*6*6*8*...
29 ;; ---------------
30 ;; 3*3*5*5*7*7*...
32 (define (pi iterations)
33 (* 4.0
34 (product (lambda (x)
35 (if (odd? x)
36 (/ (+ x 1) (+ x 2))
37 (/ (+ x 2) (+ x 1))))
38 1
39 (lambda (x) (+ x 1))
40 iterations)))
42 (define (test-case actual expected)
43 (load-option 'format)
44 (newline)
45 (format #t "Actual: ~A Expected: ~A" actual expected))
47 (test-case (factorial 0) 1)
48 (test-case (factorial 1) 1)
49 (test-case (factorial 2) 2)
50 (test-case (factorial 3) 6)
51 (test-case (factorial 4) 24)
52 (test-case (factorial 5) 120)
53 (test-case (factorial 6) 720)
54 (test-case (factorial 7) 5040)
55 (test-case (factorial-iter 7) 5040)
57 (test-case (pi 10000) 3.1415)