SICP Exercise 3.63 sqrt-stream Louis Reasoner

Exercise 3.63.  Louis Reasoner asks why the sqrt-stream procedure was not written in the following more straightforward way, without the local variable guesses:

(define (sqrt-stream x)
  (cons-stream 1.0
               (stream-map (lambda (guess)
                             (sqrt-improve guess x))
                           (sqrt-stream x))))


Alyssa P. Hacker replies that this version of the procedure is considerably less efficient because it performs redundant computation. Explain Alyssa's answer. Would the two versions still differ in efficiency if our implementation of delay used only (lambda () <exp>) without using the optimization provided by memo-proc (section 3.5.1)?

EXPLANATION

If we do not use the local variable 'guesses', then every call to procedure sqrt-stream creates a brand-new stream. In Louis Reasoner's implementation of 'sqrt-stream', a call to:

(display-stream (sqrt-stream 100))

will result in generating the stream elements from the first element till the 100th element. Since this will be the first time the stream elements are accessed, all delayed objects will be forced when we display the stream.

If after this we call:

(display-stream (sqrt-stream 101))

a new stream is created so the evaluations to generate all elements from the first
till the 101st element will be performed again. All delayed objects will be forced again since this is a new stream that shares no state with the previous stream.

Coming to the second part of the problem, if our implementation of delay used only (lambda () <exp>) without taking advantage of memo-proc, then the two versions will differ in efficiency only to the small extent that whereas sqrt-stream maintains a single stream, Louis' implementation constructs a new stream every time it is run. Post-construction of the stream, the calls to access the stream elements will not differ in efficiency between the two implementations since in both cases, all delayed objects will be forced every time they are accessed.

The code is here.

Comments

Popular posts from this blog

SICP Exercise 2.56 differentiation rule

SICP Exercise 1.28 (Miller-Rabin Test)

SICP Exercise 4.18 a alternative strategy for interpreting internal definitions