1
(***********************************************************************)
5
(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
7
(* Copyright 2001 Institut National de Recherche en Informatique et *)
8
(* en Automatique. All rights reserved. This file is distributed *)
9
(* only by permission. *)
11
(***********************************************************************)
13
Manipulation of lists.
15
- [] is the empty list
16
- :: is the infix operator that builds list cells.
17
Hence 1 :: (2 :: []) is the list that contains 1 and 2 in this order.
20
(* interval min max = [min; min+1; ...; max-1; max] *)
22
let rec interval min max =
23
if min > max then [] else min :: interval (succ min) max
28
Case analysis on list l is written
31
| x :: tail -> ``non nil case,
32
with x (the head of l) and tail (the tail of l) available''
34
Function can perform direct case analysis on their argument,
35
if introduced by the function keyword. Hence,
50
(* filter p L returns the list of the elements in list L
51
that satisfy predicate p *)
53
let rec filter p = function
55
| a :: r -> if p a then a :: filter p r else filter p r
58
(* Application: removing all numbers multiple of n from a list of integers *)
60
let remove_multiples_of n =
61
filter (fun m -> m mod n <> 0)
64
(* The sieve itself *)
67
let rec filter_again = function
70
if n * n > max then l else n :: filter_again (remove_multiples_of n r)
72
filter_again (interval 2 max)
76
print_string "Usage: sieve <n>\n";
83
if Array.length Sys.argv <> 2 then usage () else
86
let n = int_of_string Sys.argv.(1) in
87
List.iter (fun n -> print_int n; print_string " ") (sieve n);
89
with Failure "int_of_string" ->
90
print_string "Bad integer constant";
95
if !Sys.interactive then () else main ();;