This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

[Caml-list] A (much less) frustrated beginner
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2003-12-23 (21:13) From: Aleksey Nogin Subject: Re: [Caml-list] A (much less) frustrated beginner
```On 23.12.2003 11:00, Tyler Eaves wrote:

> (*  primes2.ml
>     Prime number generator, take 2
>     Tyler Eaves <tyler@ml1.net>
>     *)
>
> exception Not_prime;;
> exception Its_Prime;;
>
> let rec isprime n primes = (
>     try
>         List.iter (fun x -> if n mod x = 0 then raise Not_prime else if sqrt
>         (float_of_int n) < (float_of_int x) then raise Its_Prime else ()) primes;
>         Printf.printf "%d is PRIME!\n" n;
>         isprime (n+2) (List.concat [primes; [n]])
>     with
>         Not_prime -> isprime (n+2) primes
>         | Its_Prime -> (Printf.printf "%d is PRIME!\n" n;
>           isprime (n+2) (List.concat [primes; [n]]))
>     );;
>
> isprime 3 [2];;

Minor thing - instead of "List.concat [primes; [n]]", you can write just
"primes @ [n]" ("@" is an infix list append operator).

Also, List.iter is still somewhat imperative. Here is a slight modification:

let rec list_exists f n = function
[] -> false
| hd :: _ when hd > n -> false
| hd :: tl -> f hd && (list_eists f n tl) ;;

let rec print_primes n primes =
let limit = int_of_float (sqrt (float_of_int n))) in
if list_exists (fun x -> n mod x = 0) limit primes then
print_primes (n + 2) primes
else begin
Printf.printf "%d is PRIME!\n" n;
print_primes (n+2) (primes @ [n])
end;;

print_primes 3 [2];;

--
Aleksey Nogin