Version française
Home     About     Download     Resources     Contact us    
Browse thread
[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: -- (:)
From: Aleksey Nogin <aleksey@n...>
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

Home Page: http://nogin.org/
E-Mail: nogin@cs.caltech.edu (office), aleksey@nogin.org (personal)
Office: Jorgensen 70, tel: (626) 395-2907

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners