# weima learns to program

my attempt to do the exercises in sicp.

## Wednesday, December 15, 2010

### sicp exercise 3.52

;; 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.

(define (stream-enumerate-interval low high)
(if (> low high)
the-empty-stream
(cons-stream low
(stream-enumerate-interval (+ 1 low) high))))

(define (display-line x) (newline) (display x))

(define (stream-for-each proc s)
(if (stream-null? s)
'done
(begin (proc (stream-car s))
(stream-for-each proc (stream-cdr s)))))

(define (display-stream s)
(stream-for-each display-line s))

(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))
(newline)
(display (stream-ref y 7))(newline)
(display-stream z)(newline)
(display sum)(newline)

;; Output:
; 136
;
; 10
; 15
; 45
; 55
; 105
; 120
; 190
; 210
; 210
;... done

;; If the procedure (delay <exp>) is implemented as (lambda() <exp>) without the memo-proc, then everytime the stream is referenced, the #promise is evaluated again. If mem-proc is used, the #promise's earlier computed value is returned instead of evaluating the procedure again.