gscheme/examples/primes.scm

33 lines
715 B
Scheme

(define primes
;;; check for composite numbers by testing the
;;; most probable divisors first
(let* ((start (list 2))
(end start))
(letrec
((composite?
(lambda (v l)
(let ((d (car l)))
(if (> (* d d) v) #f
(if (zero? (remainder v d)) #t
(composite? v (cdr l)))))))
(findnext
(lambda (v)
(if (composite? v start)
(findnext (+ v 1)) v))))
(lambda ()
(let* ((current (car end))
(next (findnext (+ current 1)))
(p (cons next '())))
(set-cdr! end p)
(set! end p)
current)))))
(define displayprimes
(lambda (n)
(if (not (zero? n))
(begin
(display (primes)) (newline)
(displayprimes (- n 1))))))
(displayprimes 14)