1 (define (memo-proc proc)
2 (let ((already-run? false) (result false))
6 (begin (set! already-run? true)
10 (define-syntax mydelay
11 (rsc-macro-transformer
14 `(memo-proc (lambda () ,exp)))))
16 (apply xfmr (cdr e))))))
18 (define (myforce delayed-object)
21 (define-syntax cons-stream
22 (rsc-macro-transformer
23 (let ((xfmr (lambda (x y) `(cons ,x (mydelay ,y)))))
25 (apply xfmr (cdr e))))))
27 (define (stream-car s)
29 (define (stream-cdr s)
31 (define stream-null? null?)
32 (define the-empty-stream '())
34 (define (integers-starting-from n)
35 (cons-stream n (integers-starting-from (+ n 1))))
37 (define (stream-ref s n)
40 (stream-ref (stream-cdr s) (- n 1))))
41 (define (stream-map proc s)
44 (cons-stream (proc (stream-car s))
45 (stream-map proc (stream-cdr s)))))
46 (define (stream-for-each proc s)
49 (begin (proc (stream-car s))
50 (stream-for-each proc (stream-cdr s)))))
52 (define (stream-enumerate-interval low high)
57 (stream-enumerate-interval (+ low 1) high))))
58 (define (stream-filter pred s)
61 (let ((scar (stream-car s)))
63 (cons-stream scar (stream-filter pred (stream-cdr s)))
64 (stream-filter pred (stream-cdr s))))))
66 (define (display-stream s)
67 (stream-for-each display-line s))
68 (define (display-line x)
72 (define (test-case actual expected)
77 (display "Expected: ")
81 ;; Exercise 3.52. Consider the sequence of expressions
87 (define seq (stream-map accum (stream-enumerate-interval 1 20)))
89 (define y (stream-filter even? seq))
91 (define z (stream-filter (lambda (x) (= (remainder x 5) 0))
95 ;; 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136
98 ;; 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 210
100 (display '(10 15 45 55 105 120 190 210))
102 ;; What is the value of sum after each of the above expressions is evaluated? What is the printed response to evaluating the stream-ref and display-stream expressions? Would these responses differ if we had implemented (delay <exp>) simply as (lambda () <exp>) without using the optimization provided by memo-proc ? Explain.
104 (define (memo-proc proc)
105 proc) ;; get rid of the optimization
110 (define seq (stream-map accum (stream-enumerate-interval 1 20)))
112 (define y (stream-filter even? seq))
114 (define z (stream-filter (lambda (x) (= (remainder x 5) 0))
120 ;; *6 19 *24 *30 37 45 *54 *64 75 87 *100 *114 129 145 *162
123 ;; *15 167 173 *180 188 197 207 218 *230 243 257 272 288 *305 323 342 362
125 (display '(15 180 230 305))