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 (merge-streams-1 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-1 (tail s1) (tail s2))))))))

; Inspiration: Jens Axel Soegaard.
(define (append-streams s1 s2)
    ((empty-stream? s1) s2) 
    ((empty-stream? s2) s1)
      (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))))