Anonymous user
Primality by trial division: Difference between revisions
m
→Infinite list of primes: Rewritten a bit
m (→Infinite list of primes: Rewritten a bit) |
|||
Line 1,865:
=== Infinite list of primes ===
====
This example uses infinite lists (streams)
<lang Racket>#lang lazy
(define nats (cons 1 (map add1 nats)))
(define (sift n l) (filter (λ(x) (not (zero? (modulo x n)))) l))
(define (sieve l) (cons (first l) (sieve (sift (first l) (rest l)))))
(define primes (sieve (rest nats)))
▲(!! (take-upto 100 primes))</lang>
Same algorithm as above, but now using threads and channels to produce a channel of all prime numbers (similar to newsqueak). The macro at the top is a convenient wrapper around definitions of channels using a thread that feeds them.
▲==== using threads and channels ====
<lang Racket>#lang racket
▲(define-syntax (bg-loop stx)
(syntax-case stx ()
[(_ (name . args) expr ...)
(with-syntax ([out! (datum->syntax stx 'out!)])
#'(
(define (out! x) (channel-put out x))
(thread (λ() (let loop () expr ... (loop))))
out))]))
(define
(define-thread-loop (filter pred? c)
(
(define (sift n c) (filter
(define-thread-loop (
(
(define primes (let ([ns (nats)]) (channel-get ns) (sieve
(for/list ([i 25] [x (
▲ (set! c (sift x c))))
▲==== using generators ====
Yet another variation of the same algorithm as above, this time using generators.
<lang Racket>#lang racket
(require racket/generator)
(define nats (generator () (for ([i (in-naturals 1)]) (yield i))))
(define (filter pred g)
Line 1,926 ⟶ 1,911:
(define (sieve g)
(generator ()
(let loop ([g g]) (let ([x (g)]) (yield x) (loop (sift x g))))))
(define primes (begin (nats) (sieve nats)))
(for/list ([i 25] [x (in-producer primes)]) x)</lang>
=={{header|REBOL}}==
|