summaryrefslogtreecommitdiff
path: root/sieve/sundaram.scm
blob: 8e5bf530896eb55e281d3271af408ad563d442ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48



(add-to-load-path (dirname (current-filename)))

(import
    (srfi srfi-41)
    (extra-functional)
    (my-streams))



(define base (stream-from 1))



(define (f i j)
    (+ i j (* 2 i j)))



(define-stream (i-stream i)
    (stream-map
        (part f i)
        (stream-from i)))



(define ij-stream
    (stream-let loop ((n 1) (strm (i-stream 1)))
        (let* ((next (+ n 1))
               (cutoff ((curry >) (stream-car (i-stream next))))
               (available (stream-take-while cutoff strm))
               (remaining (stream-drop-while cutoff strm)))
            (stream-append available (loop next (stream-merge remaining (i-stream next)))))))



(define-stream (sieve input)
    (stream-map
        (compose (part + 1) (part * 2))
        (stream-ordered-diff input ij-stream)))



(define sundaram (stream-cons 2 (sieve base)))