; Imperative prime sieve in Scheme. (define (sieve-out pivot number-list) (let ((i number-list) (result '()) (result-tail '())) (while (not (null? i)) (if (not (zero? (modulo (car i) pivot))) (if (pair? result) (begin (set-cdr! result-tail (cons (car i) '())) (set! result-tail (cdr result-tail))) (begin (set! result (list (car i))) (set! result-tail result)))) (set! i (cdr i))) result)) (define (sieve number-list) (let ((i number-list) (result '()) (result-tail '())) (while (not (null? i)) (if (pair? result) (begin (set-cdr! result-tail (cons (car i) '())) (set! result-tail (cdr result-tail))) (begin (set! result (cons (car i) '())) (set! result-tail result))) (set! i (sieve-out (car i) i))) result)) (define (find-primes-to to) (let ((numbers '()) (i to)) (while (> i 2) (set! numbers (cons i numbers)) (set! i (1- i))) (sieve numbers)))