Skip to content

Instantly share code, notes, and snippets.

@Sophia-Gold
Created March 6, 2020 19:39
Show Gist options
  • Save Sophia-Gold/5871e9b796ec750e79552ad6a5554934 to your computer and use it in GitHub Desktop.
Save Sophia-Gold/5871e9b796ec750e79552ad6a5554934 to your computer and use it in GitHub Desktop.
OCaml arithmetic with no overflow
(* From http://caml.inria.fr/pub/ml-archives/caml-list/2004/06/8730fc362310ad9db0c2239b5b815a22.en.html *)
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment