I was trying to write some code using the Int32
library, but I hit a type error:
let x : int = 7;
Int32.abs(x)
This has type:
int
But somewhere wanted:
int32
I was a bit surprised by this, because in other languages int
is just an alias for int32
.
My questions are:
Int32.abs
but not Int.abs
, for example)Here's a comparison of the various integer data types available, their type, associated module and literal syntax:
let int : int = Pervasives.abs(42);
let int32 : int32 = Int32.abs(42l);
let int64 : int64 = Int64.abs(42L);
let nativeint : nativeint = Nativeint.abs(42n);
Note that Pervasives
is opened automatically, so you therefore do not need to have its functions qualified like above.
ìnt
is natively 31-bit on 32-bit platforms and 63-bit on 64-bit platforms, and the type you'd use unless you need the exact arithmetic semantics provided by int32
, int64
or nativeint
. In32
, Int64
, and Nativeint
all contain this (or a similar) note:
Performance notice: values of type int32 occupy more memory space than values of type int, and arithmetic operations on int32 are generally slower than those on int. Use int32 only when the application requires exact 32-bit arithmetic.
I hope that answers your questions.
Edit: When using BuckleScript to compile to JavaScript, which is quite common with Reason, the semantics are slightly different:
int32
and int64
behave the sameint
behaves like int32
nativeint
is mostly treated like float
, with a few exceptions to be more integer-like.Source: https://bucklescript.github.io/docs/en/difference-from-native-ocaml.html#integers