As it is, the random
procedure is called only once because you didn't recursively call input_stream
again, that's why all the random numbers in the stream are in fact, the same number. You have to guarantee that the pseudo-random number generator is called every time a new value is cons
'ed, for example:
(define (random-stream n)
(cons (random n) (delay (random-stream n))))
Now this stream will contain random numbers in the range 0-9:
(define input_stream (random-stream 10))
Note: I defined n
as a parameter jut to make the generated stream parameterizable, it'll work just as well with a fixed value:
(define (random-stream)
(cons (random 10) (delay (random-stream))))
(define input_stream (random-stream))
For example, to access the first three elements:
(car input_stream)
=> 9 ; random number between 0-9
(car (force (cdr input_stream)))
=> 7 ; random number between 0-9
(car (force (cdr (force (cdr input_stream)))))
=> 8 ; random number between 0-9
Or in general, for generating a list of m
random elements from 0 (inclusive) to n
(exclusive):
(define (stream-take s m)
(if (zero? m)
'()
(cons (car s)
(stream-take (force (cdr s)) (sub1 m)))))
(stream-take (random-stream 10) 20) ; n=10, m=20
=> '(3 3 3 7 0 7 3 2 3 7 6 0 6 4 1 4 6 1 6 9) ; 20 random numbers between 0-9