3 (define (stream-car s) (car s))
4 (define (stream-cdr s) (force (cdr s)))
6 (define (stream-ref s n)
9 (stream-ref (stream-cdr s)
12 (define (stream-map proc s)
15 (cons-stream (proc (stream-car s))
16 (stream-map proc (stream-cdr s)))))
18 (define (stream-filter pred? s)
19 (cond [(stream-null? s) the-empty-stream]
20 [(pred? (stream-car s))
21 (cons-stream (stream-car s)
22 (stream-filter pred? (stream-cdr s)))]
23 [else (stream-filter pred? (stream-cdr s))]))
25 (define (stream-for-each proc s)
30 (stream-for-each proc (stream-cdr s)))))
32 (define (display-stream s)
33 (stream-for-each display-line s))
35 (define (display-line x)
39 ;; stream-enumerate-interval
40 (define (stream-enumerate-interval low high)
44 (stream-enumerate-interval (+ low 1)
53 (define x (stream-map show (stream-enumerate-interval 0 10)))
55 This will display 0. The reason is that, we can reduce this expression
60 (cons 0 (delay (stream-enumerate-interval 1 10))))
62 (stream-map show (stream-cdr
63 (cons 0 (delay (stream-enumerate-interval 1 10)))))))
65 This will print 0 and the rest of the computation is delayed.
69 stream-ref will keep calling stream-cdr on the stream for 5 times. This will 'force' evaluation
70 of the delayed operations.
73 (delay (stream-map show (stream-enumerate-interval 1 10))))
75 Calling stream-cdr once, this expression becomes
77 (cons-stream (show (stream-car (stream-enumerate-interval 1 10)))
79 (stream-cdr (stream-enumerate-interval 1 10)))))
84 (cons 1 ;; also prints 1
85 (delay (stream-map show
86 (stream-cdr (stream-enumerata-interval 1 10))))))
88 As can be seen, this will print 1 and the rest are 'delayed'.
90 Think of the output of (stream-enumerate-interval 0 10) as:
98 (delay (cons 10 the-empty-stream))...)
102 Now, x is (stream-map show s). This is equiv of:
104 (cons (show (stream-car s))
105 (delay (stream-map show (stream-cdr s)))
107 This will first print 0, when defined.
109 (stream-ref 5 x) is equiv to:
111 (stream-car (stream-cdr (stream-cdr (stream-cdr (stream-cdr (stream-cdr x))))))
113 This will make the stream-map work on the 5 delayed computations and hence
114 numbers from 1 to 5 printed on the screen. Together will that, the value of
115 (stream-ref s 5) == 5 will also be printed.
119 This will print 6 and 7 along with the value of the expression (i.e. 7).
127 (define x (stream-map show (stream-enumerate-interval 0 10)))