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: Luc Maranget <luc.maranget@i...>
Subject: Re: [Caml-list] Runtime overflow and what to do
> Hi,
> 
> 
> suppose I use the following code for fact
> 
> let rec fact n = if n <= 1 then 1 else n * fact (n - 1) ;;
> 
> Because an integer number is represented by a fixed number of bytes I will
> get a runtime overflow if n is chosen too large.
> 
> Is there in Ocamel a workaround to cope with this problem . Something like "
> Onoverflow goto .. " in imperative languages.
> 
> Thx
> 
> Scott
> 
> 

There is no such feature as a Onoverflow goto, because
Ocaml (and not OCamel...) default integers are not << real >> integers,
but machine integers on some size (typically 31 or 63) bits.

This means that maxint + 1 is minint and basically this is the
behavior of C.

I guess the reason why is avoiding putting non-obvious tests
everywhere.

Most of the time you do not need those tests.
  * If you want ``real'' integers, you can use some arbitrary
    precision library (Num, etc.), overflow detection would  not help
    here anyway.

  * If you want to be warned on overflow, you have to devise the tests
    by yourself, and then you can use an exception as your
    Onoverflow goto
     An easy one :

expection Overflow

let protected_incr x =
  let y = x+1 in
  if y > x then y
  else raise Overflow

try
  .... incr (..)
with
| Overflow -> ... do whatever you can ... 

Hope it helps.

--Luc
               

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