For variants without parameters, they are simply stored as an OCaml integer without boxing and the integers are in ascending order within one type.
For example, let's define a function peek
to see the real integer value of a variant:
let peek x = ((Obj.magic (Obj.repr x)):int);;
I define a type:
type t1 = Apple | Orange;;
then peek Apple;;
will return 0
and peek Orange;;
will return 1
.
However, if I define 2nd type
type t2 = Empty | Node;;
then again peek Empty;;
will return 0
and 1
for peek Node
.
Basically, the increment of the integers for variants are not global.
I have then questions:
Since OCaml won't maintain type information during runtime, how can runtime knows an integer being a normal integer or a variant without parameter?
Further, how OCaml runtime tell the differences between two variants that actually belong to different types? e.g., how can it tell the diff between Apple and Empty as they are both 0?
open-types
? – Jackson Tale