Version française
Home     About     Download     Resources     Contact us    
Browse thread
Re: [Caml-list] Runtime overflow and what to do
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Xavier Leroy <xavier.leroy@i...>
Subject: Re: [Caml-list] Runtime overflow and what to do
> So it is not easy, perhaps even impossible if the processor doesn't set a
> flag .

It is possible, but slow and not pretty!  For example, here is Caml
code that performs integer addition and detects overflows:

exception Integer_overflow

let no_overflow_add a b = 
  if (a lxor b) lor (a lxor (lnot (a+b))) < 0  (* no kidding! *)
  then a + b
  else raise Integer_overflow

Multiplication is left as an exercise for the readers :-)

My advice would be to use bignums; they are a bit slower, but at least
you get the exact result in all cases.

- Xavier Leroy
-------------------
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