3.5.2 Infinite Streams
2024-05-19 Sun
- We can use streams to represent infinite sequences.
For example, this is the definition of the stream of positive integers:
(define (integers-starting-from n) (cons-streams n (integers-starting-from (+ n 1)))) (define integers (integers-starting-from n))
``Our programs will never know that the entire infinite stream is not there.''
We can now define other infinite streams based on this one, e.g.:
(define (divisible? x y) (= (remainder x y) 0)) (define no-sevens ;; streams of integers that are not divisible by 7 (stream-filter (lambda (x) (not (divisible? x 7))) integers)) (stream-ref no-sevens 100) ;; => 117
- Authors show the analog way to define the infinite streams of Fibonacci numbers.
- Authors show the method, known as the ``sieve of Eratosthenes'', to construct the infinite streams of prime numbers.
integers
isdefined by specifying ``generating'' procedures that explicitly compute the stream elements one by one. An alternative way to specify streams is to take advantage of delayed evaluation to define streams implicitly. (328)
Here is an infinite streams of ones:
(define ones (cons-stream 1 ones))
Consider the following operation, which uses the generalized version of
stream-map
from exercise 3.50:(define (add-stream s1 s2) (stream-map + s1 s2))
Now
integers
can be defined as follows:(define integers (cons-stream 1 (add-streams ones integers)))
Exercise 3.53
Exercise:
Without running the program, describe the elements of the stream defined by
(define s (cons-stream 1 (add-streams s s)))
Answer:
The elements of the streams are the powers of 2.
s
is the list whose car
is 1 and whose cdr
is the promise to
execute (add-stream s s)
.
Forcing the cdr
of s
gives us the list whose car
is 2 and whose
cdr
is the promise to execute (add-stream (stream-cdr s)
(stream-cdr s))
.
Forcing the cdr
of the cdr
of s
gives us the list whose car is 4
and whose cdr
…