3 (#%require (only racket random))
5 (define (stream-car s) (car s))
6 (define (stream-cdr s) (force (cdr s)))
8 (define (stream-ref s n)
11 (stream-ref (stream-cdr s)
14 (define (stream-map proc . argstreams)
15 (if (stream-null? (car argstreams))
18 (apply proc (map stream-car argstreams))
20 (cons proc (map stream-cdr argstreams))))))
22 (define (scale-stream stream factor)
23 (stream-map (lambda (x) (* x factor)) stream))
26 (define (stream-map proc s)
29 (cons-stream (proc (stream-car s))
30 (stream-map proc (stream-cdr s)))))
33 (define (stream-filter pred? s)
34 (cond [(stream-null? s) the-empty-stream]
35 [(pred? (stream-car s))
36 (cons-stream (stream-car s)
37 (stream-filter pred? (stream-cdr s)))]
38 [else (stream-filter pred? (stream-cdr s))]))
40 (define (stream-for-each proc s)
45 (stream-for-each proc (stream-cdr s)))))
47 (define (display-stream s)
48 (stream-for-each display-line s))
50 (define (display-line x)
54 ;; stream-enumerate-interval
55 (define (stream-enumerate-interval low high)
59 (stream-enumerate-interval (+ low 1)
64 (define (square x) (* x x))
65 (define (smallest-divisor n)
67 (define (find-divisor n test-divisor)
68 (cond ((> (square test-divisor) n) n)
69 ((divides? test-divisor n) test-divisor)
70 (else (find-divisor n (+ test-divisor 1)))))
71 (define (divides? a b)
72 (= (remainder b a) 0))
75 (= (smallest-divisor n) n))
79 (define (integers-starting-from n)
81 (integers-starting-from (+ n 1))))
83 (define integers (integers-starting-from 1))
85 (define (add-streams s1 s2)
88 ;; integers which are not a multiple of 7
89 (define (divisible? a b) (= 0 (remainder a b)))
92 (stream-filter (lambda (x) (not (divisible? x 7)))
97 (cons-stream a (fib-gen b (+ a b))))
99 (define fibs (fib-gen 0 1))
102 (define (sieve stream)
105 (sieve (stream-filter (lambda (x)
106 (not (divisible? x (stream-car stream))))
107 (stream-cdr stream)))))
109 (define primes (sieve (integers-starting-from 2)))
111 (define (interleave s1 s2)
112 (if (stream-null? s1)
114 (cons-stream (stream-car s1)
115 (interleave s2 (stream-cdr s1)))))
119 (list (stream-car s) (stream-car t))
121 (stream-map (lambda (x) (list (stream-car s) x))
123 (pairs (stream-cdr s) (stream-cdr t)))))
125 (define (integral integrand initial-value dt)
127 (cons-stream initial-value
128 (add-streams (scale-stream integrand dt)