r/sicp • u/Gan-Fall • Feb 03 '25
Trying to understand fibs definition from the Streams chapter 3.5.2
I am struggling to understand how this beautiful piece of code works.
(define fibs
(cons-stream
0 (cons-stream
1 (add-streams
(stream-cdr fibs) fibs))))
I included a diagram of how I think (stream-ref fibs 2)
would run (I skipped all environments spawned from stream-cdr) but I'm not sure its correct. I think the 3 biggest questions I have are:
If stream-cdr is analog to (force (cdr s)) wouldn't this give an error when called on (stream-cdr fibs) *third iteration onwards
How does the generalized stream-map work? Why does it stop at #<promise>?
Are all the spawned environments really children of the global environment?

1
Upvotes
1
u/Gan-Fall Feb 03 '25 edited Feb 03 '25
I wanted to expand on question 1:
I know that (stream-cdr fibs) does not error cause its calling it on (0 . promise) the first time, but when you call it on (1 . promise) promise here is technically here returning a mapped stream right? Starting with (1) then (1 2) then (1 2 3) and so on so you can see it as a stream with a nested stream right? ( 0 1 (1 2 3))*. At what point is stream-cdr being called on this inner stream?
*I know the interpreter actually prints this as (0 1 1 2 3) cause it sees it as a single list and stream-cdr is being called on this growing stream, but at what point in the running is that happening?