Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

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: Alessandro Baretta <alex@b...>
Subject: Re: [Caml-list] Runtime overflow and what to do

Scott J, wrote:
> Hi,
> So it is not easy, perhaps even impossible if the processor doesn't set 
> a flag .
> e.g. fact n begins first with a lis of negative numbers (after overflow) 
> then comes again a list with positive numbers and then it remains = 0
> Scott

If your problem is only the factorial function, then you can 
calculate statically (i.e. at source-code writing time) the 
value of the maximum integer whose factorial will fit in 
O'Caml's representation of integers, and test against that, 
once and for all, before entering the recursive calculation.

exception overflow
let max_fact_arg = ...

let fact =
let rec rec_fact n =
   if n <= 0 then 1
   else n * rec_fact (n-1)
in function
| x when x <= max_fact_arg -> rec_fact n
| _ -> raise Overflow

This strategy allows to incur in hardly any runtime costs 
for the check, and it also allows you prove more easily that 
your program will not raise runtime Overflow exceptions (the 
precondition for not entering the exception raising branch 
does not have to be propagated out of a recursive function 


To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: