#!/bin/sh
exec ${GUILE-guile} -e '(ttn-do primes)' -s $0 "$@" # -*- scheme -*-
!#
;;; primes

;; Copyright (C) 2009, 2010, 2011 Thien-Thi Nguyen
;;
;; This file is part of ttn-do, released under the terms of the
;; GNU General Public License as published by the Free Software
;; Foundation; either version 3, or (at your option) any later
;; version.  There is NO WARRANTY.  See file COPYING for details.

;;; Commentary:

;; Usage: primes LIMIT
;;
;; Display prime numbers in the range [2,LIMIT], one per line.
;; If LIMIT is less than two or not a number, do nothing.

;;; Code:

(define-module (ttn-do primes)
  #:export (primes
            main)
  #:use-module ((ice-9 rdelim) #:select (write-line))
  #:use-module ((ttn-do zzz banalities) #:select (check-hv))
  #:use-module ((ttn-do zzz personally) #:select (accumulator
                                                  FE)))

;; Return a list of prime numbers in the range [2,@var{limit}].
;;
(define (primes limit)
  (let ((all (accumulator)))
    (and (<= 2 limit) (all 2))
    (do ((n 3 (+ 2 n)))
        ((< limit n))
      (and (let ((mid (sqrt n)))
             (let loop ((ls (all)))
               (or (null? ls)
                   (let ((head (car ls)))
                     (or (< mid head)
                         (and (not (zero? (remainder n head)))
                              (loop (cdr ls))))))))
           (all n)))
    (all)))

(define (main args)
  (check-hv args '((package . "ttn-do")
                   (version . "1.0")
                   (help . commentary)))
  (or (null? (cdr args))
      (FE (primes (or (string->number (cadr args)) ; slack
                      0))
          write-line)))

;;; primes ends here