Only primes numbers filter in OCAML

Submitted by fabio on Sat, 2007-12-08 14:56.

A small OCAML algorithm to filter out non prime number from a list of given numbers.

(*
Fabio Varesano - 2007/05/11
Delete non prime numbers from a list of integers
(The list must start from 2 and contains all numbers)
*)

let primefilter list =
  match list with
    | [] -> []
    | x::xs -> let primetest = function y -> y mod x <> 0
             in x::(List.filter primetest xs);;


primefilter [2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20;21;22];;

let rec primefilter list =

Submitted by Anonymous (not verified) on Thu, 2008-05-15 23:10.

let rec primefilter list = match list with
| [] -> []
| x::xs -> let primetest = function y -> y mod x <> 0
in x::(List.filter primetest (primefilter xs));;

# primefilter [2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20;21;22];;
- : int list = [2; 3; 5; 7; 11; 13; 17; 19]

This returns [2; 3; 5; 7; 9;

Submitted by Anonymous (not verified) on Wed, 2008-01-09 03:02.

This returns [2; 3; 5; 7; 9; 11; 13; 15; 17; 19; 21];;

and last time I checked, 9, 15, and 21 are composite :)

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <img> <h2> <h3> <h4> <b>
  • Lines and paragraphs break automatically.
  • Images can be added to this post.
  • You may use [inline:xx] tags to display uploaded files or images inline.

More information about formatting options

3 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.