File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ #lang racket
2
+ (require "stream.rkt " )
3
+
4
+ (define (integers-starting-from n)
5
+ (cons-stream n (integers-starting-from (+ n 1 ))))
6
+
7
+ (define (divisible? n x)
8
+ (zero? (remainder n x)))
9
+
10
+ ;;; https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
11
+ (define (sieve stream )
12
+ (cons-stream
13
+ (stream-car stream )
14
+ (sieve (stream-filter
15
+ (lambda (x)
16
+ (not (divisible? x (stream-car stream ))))
17
+ (stream-cdr stream )))))
18
+
19
+ (module+ test
20
+ (require rackunit)
21
+
22
+ (test-case "Test for divisible? "
23
+ (check-true (divisible? 12 2 ))
24
+ (check-true (divisible? 12 6 ))
25
+ (check-false (divisible? 3 4 ))
26
+ )
27
+
28
+ (test-case "Test for sieve "
29
+ (define primes (sieve (integers-starting-from 2 )))
30
+ (check-equal? (stream-ref primes 50 ) 233 )
31
+ )
32
+ )
You can’t perform that action at this time.
0 commit comments