20-CS-4003-001 Organization of Programming Languages Fall 2017
Streams

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures           Code

Implementing a Sieve for Prime Numbers

;; A stream version of finding prime numbers using a 
;; sieve.  The advantage of doing this is recomputation 
;; is not necessary should the user decide to acquire 
;; more numbers than originally anticipated.
(define int-stream-builder$
  (lambda (x)
    (cons x 
          (lambda () (int-stream-builder$ (+ 1 x))))))

;; A counter as a stream - produces tokens 2, 3, ...
(define counter (int-stream-builder$ 2))

;; Create a stream of numbers, none of which is a 
;; multiple of num and all of which are members of S
(define filter-mults$
  (lambda (num S$)
    (if (= (modulo (car S$) num) 0)
        (filter-mults$ num ((cdr S$)))
        (cons (car S$) 
              (lambda () 
                (filter-mults$ num ((cdr S$))))))))

;; Filter out multiples of 2, then multiples of 3, 
;; then multiples of 4, ...
(define sieve$
  (lambda (S$)
    (cons 
      (car S$)
      (lambda() 
        (sieve$ (filter-mults$ (car S$) ((cdr S$))))))))
 
(define primes (sieve$ counter))

;; take the first n elements of a stream
(define take
   (lambda (n S)
      (if (or (null? S) (= n 0))
          '()
          (if (and (not (null? (cdr S)))
                   (procedure? (cdr S)))
              (cons (car S)
                    (take (- n 1) ((cdr S))))
              (cons (car S)
                    (take (- n 1) (cdr S)))))))
 
;; A list of the first 100 primes
(define firstprimes (take 100 primes))
 -  The code to the left implements a sieve to find the 100 smallest prime numbers using streams. Except for int-stream-builder, procedures operate the same way as in the solution of the previous slide but are renamed slightly and in some cases (cdr S) becomes ((cdr S)), (lamdba () ...) is added, and no test for '() is used to terminate a list (streams are infinite so there is no need for this). The different implementation of int-stream-builder just creates the stream version of counter. Run it like this:
   prompt> (sieve counter)
   ;Value 11: (2 3 5 7 11 13 17 19 23 29 31 37 41 43
   47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 
   127 131 137 139 149 151 157 163 167 173 179 181 191 
   193 197 199 211 223 227 229 233 239 241 251 257 263
   269 271 277 281 283 293 307 311 313 317 331 337 347 
   349 353 359 367 373 379 383 389 397 401 409 419 421 
   431 433 439 443 449 457 461 463 467 479 487 491 499 
   503 509 521 523 541)
The main problem with this approach is that if more prime numbers need to be generated all of the computation to produce the first 100 numbers above will be lost. The stream solution on the next slide eliminates this problem.