Streams in Scheme
How does the following process work:
(define integers
(cons-stream 1
(stream-map (lambda (x) (+ x 1))
开发者_高级运维 integers))
The important thing to realize here that only those expressions are evaluated which are neccessary to calculate the element of the list you're accessing.
So when you access the first element, it evaluates the first argument to cons-stream
which is 1
.
When you access the second element, it evaluates the first element of stream-map (lambda (x) (+ x 1)) integers
. For that it needs to get the first element of integers
which is 1
and then adds 1
to that and you get 2
.
When you access the third element, it evaluates the second element of stream-map (lambda (x) (+ x 1)) integers
. So it takes the second element of integers
(2
) and adds 1
to that to get 3
. And so on.
精彩评论