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

Exercise solution:
A stream of factorial numbers


(define facts
  (cons-stream 1 
              (combine-streams * (tail nat-nums) facts)))

; Useful functions:

(define nat-nums
  (cons-stream 1
               (add-streams (constant-stream 1) nat-nums)))

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

(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))))))

; assume infinite streams:
(define (combine-streams bin-fn s1 s2)
 (let ((h1 (head s1))
       (h2 (head s2)))
   (cons-stream 
    (bin-fn h1 h2)
    (combine-streams bin-fn (tail s1) (tail s2)))))