Browse thread
[Caml-list] More or bignums/ints
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: | 2004-06-14 (15:55) |
From: | Xavier Leroy <xavier.leroy@i...> |
Subject: | Re: [Caml-list] More or bignums/ints |
Dear John, > 1. Is there a way to catch overflow exceptions within an entire > computation? > 2. Is there a way to tell OCaml that ints really are either > (a) bignums or > (b) overflow-protected ints (as in SML/NJ, for instance) Solution (a) is problematic because of literals. It's easy to redefine the infix `+' operator to mean "bignum addition", and similarly for other arithmetic operators, but OCaml has no syntax for bignum literals, e.g. to get the bignum 123 one needs to type Int 123 or num_of_string "123". A Camlp4 syntax extension could possibly do the job, however. Solution (b) is much easier, provided you don't care much for performance (probably true for an intro course). Stick the following definitions in, say, CS101.ml exception Overflow let ( + ) a b = let c = a + b in if (a lxor b) lor (a lxor (lnot c)) < 0 then c else raise Overflow let ( - ) a b = let c = a - b in if (a lxor (lnot b)) lor (b lxor c) < 0 then c else raise Overflow let ( * ) a b = let c = a * b in if Int64.of_int c = Int64.mul (Int64.of_int a) (Int64.of_int b) then c else raise Overflow let ( / ) a b = if a = min_int && b = -1 then raise Overflow else a / b [Note that the definition of ( * ) above assumes a 32-bit processor. Something even less efficient is required to work both on 32- and 64-bit architectures.] Compile this source to CS101.cmo and make sure that the module CS101 is linked and opened in the students' code. For instance, with the interactive toplevel loop, make them stick #load "/path/to/CS101.cmo";; #directory "/path/to";; open CS101;; in $HOME/.ocamlinit, and voila, every time they start ocaml, they get overflow-protected integers. Don't even think of modifying the OCaml bytecode interpreter so that the arithmetic operations of the abstract machine perform overflow detection: some code in the standard library and the compilers rely on modulo arithmetic. Hope this helps, - Xavier ------------------- 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