Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Finite streams

(define (stream . element-list)
  (if (null? element-list)
      (cons-stream (car element-list)
                   (apply stream (cdr element-list)))))

; Here is all necessary stream stuff:

(define-syntax cons-stream
  (syntax-rules ()
    ((cons-stream x y)
     (cons x (delay y)))))

(define head car)

(define (tail stream) (force (cdr stream)))

(define empty-stream? null?)

(define the-empty-stream '())

(define (stream-section n stream)
  (cond ((= n 0) '())
        (else (cons (head stream)
                      (- n 1)
                      (tail stream))))))

(define (add-streams s1 s2)
 (let ((h1 (head s1))
       (h2 (head s2)))
    (+ h1 h2)
    (add-streams (tail s1) (tail s2)))))

(define (combine-streams bin-fn s1 s2)
 (let ((h1 (head s1))
       (h2 (head s2)))
    (bin-fn h1 h2)
    (combine-streams bin-fn (tail s1) (tail s2)))))

(define (constant-stream c)
  (cons-stream c (constant-stream c)))