[plt-scheme] Re: plt-scheme Digest, Vol 7, Issue 31

From: geb a (geb_a at yahoo.com)
Date: Wed Mar 15 10:55:19 EST 2006

Hello,

The following code is taken from SICP's section on
streams verbatim.  While I realize there is an
infinite recursion generating a stream of numbers,
apparently the authors felt the code would work but
drscheme seems to evaluate each infinite stream first.
 Does this have something to do with lazy evaluation
(a term I know nothing about?).  Is there some
underlying reason for this that I don't know about or
have I made some mistake with the code.

Thanks in advance for your time...

Dan Anderson

(define (stream-car stream) (car stream))

(define (stream-cdr stream) (force (cdr stream)))

(define stream-null? null?)

(define the-empty-stream '())

(define (memo-proc proc)
  (let ((already-run? false) (result false))
    (lambda ()
      (if (not already-run?)
          (begin (set! result (proc))
                 (set! already-run? true)
                 result)
          result))))

(define (delay object) (memo-proc (lambda() object)))

(define (cons-stream a b)
  (cons a (delay b)))


(define (force delayed-object)
  (delayed-object))


(define (stream-ref s n)
  (if (= n 0)
      (stream-car s)
      (stream-ref (stream-cdr s) (- n 1))))

(define (stream-map proc s)
  (if (stream-null? s)
      the-empty-stream
      (cons-stream (proc (stream-car s))
                   (stream-map proc (stream-cdr s)))))

(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 (display-line x)
  (newline)
  (display x))

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



(define (stream-filter pred stream)
  (cond ((stream-null? stream) the-empty-stream)
        ((pred (stream-car stream))
         (cons-stream (stream-car stream)
                      (stream-filter pred
                                     (stream-cdr
stream))))
        (else (stream-filter pred (stream-cdr
stream)))))


(define (integers-starting-from n)
  (cons-stream n (integers-starting-from (+ n 1))))
;
(define integers (integers-starting-from 1))
;
(define (divisible? x y) (= (remainder x y) 0))
;
(define no-sevens
  (stream-filter (lambda (x) (not (divisible? x 7)))
                 integers))
(define (sieve stream)
  (cons-stream
   (stream-car stream)
   (sieve (stream-filter
           (lambda (x)
             (not (divisible? x (stream-car stream))))
           (stream-cdr stream)))))
(stream-ref no-sevens 100)



__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 


Posted on the users mailing list.