sicp-ex-3.68



<< Previous exercise (3.67) | Index | Next exercise (3.69) >>


meteorgan




no. The program will infinitely loop. because their is no delay in (pairs (stream-cdr s) (stream-cdr t)), it will be called recursively.

I disagree @meteorgan. interleave returns a cons-stream, then it has delay. Anyway, I think this solution won't work either, because it will produce the following sequence:

(1,1) (2,2) (1,2) (3,3) (1,3) (4,4) (1,4) (5,5)....

The recursive call is always going to call to the second element of interleave, because there is no 'pivot' to do an interleaving, thus it leaves out elements like (3,4) (3,5)...(4,5) (4,6)... and so on.

@meteorgan is correct here. interleave returns a cons-stream, but interleave will never be successfully called since its second arg (pairs ...) will be evaluated first. Attempting this evaluation will result in recursion sans base-case.

@anon, it is not true that second arg of interleave is evaluated first. In the (interleave s1 s2), car of s1 is taken first then interleave calls itself with arguments changed around so that s2 is now s1 and (stream-cdr s1) becomes s2.

@anon is referring to the two arguments to interleave. You're correct that cons-stream (which appears in the definition of interleave) delays evaluation of its second argument, but (interleave s1 s2), like any ordinary procedure, must evaluate s1 and s2 first before it itself can be evaluated.






xdavidliu

Louis' implementation will recurse infinitely simply because interleave is an ordinary *function*, not a special form like cons-stream, and hence will need to fully evaluate both arguments first, since Scheme uses eager evaluation for ordinary functions. Since the second argument to interleave is a recursive call to pairs, and there is no hard-coded base case, this implementation will recurse infinitely.


WLW

I agree with posts above about infinite loop. However, for me the pairs procedure also fails with finite streams such as (stream-enumerate-interval 1 10) - I get a contract violation error message - perhaps there is another problem with code too?

That is because (stream-car s) is continually called in the lambda function, despite the recursive call of pairs passing on (stream-cdr s) so at some point s would become empty in the case of a finite stream, but stream-car would still be called. Normally this error wouldn't pop up until the end of the stream is reached through successive stream-cdr's, but this time as the entire stream is evaluate at the time of definition, it arises now itself.