CS212 Exams
Spring 1999 -
Final

Filtering a Stream


Recall that we can construct the infinite stream of whole numbers as follows:

(define wholes
  (letrec ((wholes-from (lambda (i)
                          (cons-stream i (wholes-from (+ 1 i))))))
    (wholes-from 0)))

Consider the following function which is intended to provide a filter function for streams:

(define filters p s)
  (if (null-stream? s)
      s
      (let ((rest (filters p (tails s))))
        (if (p (heads s))
            (cons-stream (heads s) rest)
            rest))))

Unfortunately, something is not right. Explain what goes wrong when, for instance, we evaluate the following question and show how the filters function should have been coded.

(filters even? wholes)

Solution

Return to CS 212 Final - Spring 1999