Blob


1 ;; Exercise 1.32. a. Show that sum and product (exercise 1.31) are both special cases of a still more general notion called accumulate that combines a collection of terms, using some general accumulation function:
3 ;; (accumulate combiner null-value term a next b)
5 ;; Accumulate takes as arguments the same term and range specifications as sum and product, together with a combiner procedure (of two arguments) that specifies how the current term is to be combined with the accumulation of the preceding terms and a null-value that specifies what base value to use when the terms run out. Write accumulate and show how sum and product can both be defined as simple calls to accumulate.
7 (define (accumulate combiner null-value term a next b)
8 (if (> a b)
9 null-value
10 (combiner (term a)
11 (accumulate combiner null-value term (next a) next b))))
13 (define (sum term a next b)
14 (accumulate + 0 term a next b))
15 (define (product term a next b)
16 (accumulate * 1 term a next b))
19 (define (accumulate combiner null-value term a next b)
20 (if (> a b)
21 null-value
22 (combiner (term a)
23 (accumulate combiner null-value term (next a) next b))))
25 ;; b. If your accumulate 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.
27 (define (accumulate-iter combiner null-value term a next b)
28 (define (iter i result)
29 (if (> a b)
30 result
31 (iter (next i) (combiner (term i) result))))
32 (iter a null-value))
35 (define (factorial n)
36 (product (lambda (x) x)
37 1
38 (lambda (x) (+ x 1))
39 n))
41 (define (factorial-iter n)
42 (product-iter (lambda (x) x)
43 1
44 (lambda (x) (+ x 1))
45 n))
47 ;; pi/4 = 2*4*4*6*6*8*...
48 ;; ---------------
49 ;; 3*3*5*5*7*7*...
51 (define (pi iterations)
52 (* 4.0
53 (product (lambda (x)
54 (if (odd? x)
55 (/ (+ x 1) (+ x 2))
56 (/ (+ x 2) (+ x 1))))
57 1
58 (lambda (x) (+ x 1))
59 iterations)))
61 (define (test-case actual expected)
62 (load-option 'format)
63 (newline)
64 (format #t "Actual: ~A Expected: ~A" actual expected))
66 (test-case (factorial 0) 1)
67 (test-case (factorial 1) 1)
68 (test-case (factorial 2) 2)
69 (test-case (factorial 3) 6)
70 (test-case (factorial 4) 24)
71 (test-case (factorial 5) 120)
72 (test-case (factorial 6) 720)
73 (test-case (factorial 7) 5040)
74 (test-case (factorial-iter 7) 5040)
76 (test-case (pi 10000) 3.1415)