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

Exercise solution:
Stream appending and stream merging


(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)
              (stream-section 
                (- n 1)
               (tail stream))))))

(define (merge-streams s1 s2)
 (cond ((empty-stream? s1) s2)
       ((empty-stream? s2) s1)
       (else (let ((h1 (head s1))
                   (h2 (head s2)))
               (cons-stream h1 
                            (cons-stream h2 (merge-streams (tail s1) (tail s2))))))))

; Inspiration: Jens Axel Soegaard.
(define (append-streams s1 s2)
  (cond
    ((empty-stream? s1) s2) 
    ((empty-stream? s2) s1)
    (else 
      (cons-stream (head s1) 
                   (append-streams (tail s1) s2)))))



; An integers stream:

(define (integers-with-lower-limit n)
 (cons-stream n 
  (integers-with-lower-limit (+ n 1))))

(define (integers-with-upper-limit n)
 (cons-stream n 
  (integers-with-upper-limit (- n 1))))

(define integers
  (cons-stream 0
    (merge-streams (integers-with-lower-limit 1)
                   (integers-with-upper-limit -1))))