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

Streams |

**Implementing a Sieve for Prime Numbers**

;; A non-stream version of finding prime numbers ;; using a sieve (define int-builder (lambda (n) (if (= n 1) '() (append (int-builder (- n 1)) (list n))))) ;; A counter as a stream - produces tokens 2, 3, ... (define counter (int-builder 545)) ;; Create a stream of numbers, none of which is a ;; multiple of num and all of which are members of S (define filter-out-mults (lambda (num S) (if (null? S) '() (if (= (modulo (car S) num) 0) (filter-out-mults num (cdr S)) (cons (car S) (filter-out-mults num (cdr S))))))) ;; Filter out multiples of 2, then multiples of 3, ;; then multiples of 4, ... (define sieve (lambda (S) (if (null? S) '() (cons (car S) (sieve (filter-out-mults (car S) (cdr S))))))) (define primes (sieve counter)) |
- |
The code to the left implements a sieve to find the smallest prime
numbers that are no bigger than 545. Procedure filter-out-mults
is primarily responsible for implementing the sieve. It takes a list
S of numbers and a single number called num and checks
each number in S to see if it is divisible by num.
The procedure returns a list of numbers that are in S and are not
divisible by num. The process is repeated for all numbers up to 545
by procedure sieve. List counter not only provides the
filter numbers but also the initial list to apply the sieve to. 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. |
||