1
(* Eratosthene's sieve *)
6
- :: is the infix operator that builds list cells.
7
Hence 1 :: (2 :: []) is the list that contains 1 and 2 in this order.
10
(* interval min max = [min; min+1; ...; max-1; max] *)
12
let rec interval min max =
13
if min > max then [] else min :: interval (succ min) max
18
Case analysis on list l is written
21
| x :: tail -> ``non nil case,
22
with x (the head of l) and tail (the tail of l) available''
24
Function can perform direct case analysis on their argument,
25
if introduced by the function keyword. Hence,
40
(* filter p L returns the list of the elements in list L
41
that satisfy predicate p *)
43
let rec filter p = function
45
| a :: r -> if p a then a :: filter p r else filter p r
48
(* Application: removing all numbers multiple of n from a list of integers *)
50
let remove_multiples_of n =
51
filter (fun m -> m mod n <> 0)
54
(* The sieve itself *)
57
let rec filter_again = function
60
if n * n > max then l else n :: filter_again (remove_multiples_of n r)
62
filter_again (interval 2 max)
66
print_string "Usage: sieve <n>\n";
73
if Array.length Sys.argv <> 2 then usage () else
76
let n = int_of_string Sys.argv.(1) in
77
List.iter (fun n -> print_int n; print_string " ") (sieve n);
79
with Failure "int_of_string" ->
80
print_string "Bad integer constant";
85
if !Sys.interactive then () else main ();;