SICP Study

6B Streams, Part 2

Part 1

Recap

(define (nth-stream n s)
  (if (= n 0)
      (head s)
      (nth-stream (-1+ n) (tail s))))

Infinite streams

(define (integers-from n)
  (cons-stream n (integers-from (1+ n))))
(define integers (integers-from 1))

Sieve of Eratosthenes

(define (sieve s)
  (cons-stream
   (head s)
   (sieve (filter (lambda (x) (not (divisible? x (head s))))
                  (tail s)))))
(define primes (sieve (integers-from 2)))
(nth-stream 20 primes)
=> 73

Part 2

Defining streams implicitly

(define (add-streams s1 s2)
  (cond ((empty-stream? s1) s2)
        ((empty-stream? s2) s1)
        (else (cons-stream (+ (head s1) (head s2))
                           (add-streams (tail s1) (tail s2))))))
(define (scale-stream c s)
  (map-stream (lambda (x) (* x c)) s))
(define ones (cons-stream 1 ones))
(define integers (add-streams integers ones))

More examples

(define (integral s initial-value dt)
  (define int
    (cons-stream initial-value
                 (add-streams (scale-stream dt s) int)))
  int)
(define fibs
  (cons-stream 0
               (cons-stream 1
                            (add-streams fibs (tail fibs)))))

Explicit delay

(define y (integral dy 1 0.001))
(define dy (map-stream square y))
(define (integral delayed-s initial-value dt)
  (define int
    (cons-stream initial-value
                 (let ((s (force delayed-s)))
                   (add-streams (scale-stream dt s) int))))
  int)
(define y (integral (delay dy) 1 0.001))
(define dy (map-stream square y))

Part 3

Normal-order evaluation

Avoiding mutable state