Posts

Showing posts from June, 2019

SICP Exercise 3.53

Exercise 3.53.   Without running the program, describe the elements of the stream defined by (define s (cons-stream 1 (add-streams s s))) SOLUTION The explanation and tests are here . EXPLANATION (add-streams s s) produces a stream the first element of which is 1 + 1 = 2. So s produces: 1, 2 ... The next element in the stream will be the addition of the next element of s with itself i.e. 2 + 2 = 4. So s will be 1, 2, 4 ... So the elements of s will be: 1, 2, 4, 8, 16, 32 ...

SICP Exercise 3.52 sequence of stream expressions

Exercise 3.52.    Consider the sequence of expressions (define sum 0) (define (accum x)   (set! sum (+ x sum))   sum) (define seq (stream-map accum (stream-enumerate-interval 1 20))) (define y (stream-filter even? seq)) (define z (stream-filter (lambda (x) (= (remainder x 5) 0))                          seq)) (stream-ref y 7) (display-stream z) What is the value of  sum  after each of the above expressions is evaluated? What is the printed response to evaluating the  stream-ref  and  display-stream  expressions? Would these responses differ if we had implemented  (delay < exp >) simply as  (lambda () < exp >)  without using the optimization provided by  memo-proc  ? Explain. SOLUTION The code and tests are here . ANALYSIS & EXPLANATION Note 1: stream-enumerate-interval produces the stream (Let’s call it s): 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 seq produces the stream: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78,