PDA

View Full Version : Tutorial : using the Num library in Ocaml


Ninja40
07-10-2003, 07:19 PM
Ok, just for the beginners, it took me a while to understand how to access libraries in Ocaml.

Say I want to write the factorial function with the Num library, which defines the num type as being either int, Big_int (large integer) or a rational fraction.

In the toplevel, one can open the precompiled library using :

# #load "nums.cma" ;;

Just writing

# open Nums ;;

doesn't open the library, but allows, like in Java or "using namespace" in C++, to forget the use of the package as a prefix to the functions.

Then one can write the factorial (I should treat the n < 0 case as an error/exception):

# let rec fact n =
if n = 0 then (num_of_int 1)
else num_of_int n */ (fact (n - 1));;
val fact : int -> Num.num = <fun>

Now let's try :

# fact 10;;
- : Num.num = Int 3628800
# fact 20;;
- : Num.num = Big_int <abstr>

:suspect: Damn !

One needs to print big_int 's. We define the custom print_num function for the num type :

# let print_num ppf x =
Format.pp_print_string ppf (string_of_num x);;

We then install this print function in the toplevel :

# #install_printer print_num;;

Now we try again :

# fact 100 ;;
- : Num.num =
9332621544394415268169923885626670049071596826438162
1468592963895217599993229915608941463976156518286253
697920827223758251185210916864000000000000000000000000

Ninja40
07-10-2003, 07:23 PM
In Scheme (DrScheme), it's much simpler since the equivalent of the Ocaml Num type is turned on by default :

(define (fact n)
(if (= n 0) 1
(* n fact (- n 1))))

(fact 100)

93326215443944152681699238856266700490715968264381
6214685929638952175999932299156089414639761565182862
5369792082722375825118521091686400000000000000000000
0000