0
votes

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:

  1. Since OCaml won't maintain type information during runtime, how can runtime knows an integer being a normal integer or a variant without parameter?

  2. 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?

1
you will see that exceptions, open-types, and polymorphic variants are different.nlucaroni
@nlucaroni what do u mean by open-types?Jackson Tale

1 Answers

4
votes

The runtime can't make the difference between 0, Apple and Empty but it doesn't need to. The compiler checks the types so that Apple will always be used with type t1 and not t2 or int. Once the types are checked by the compiler, you no longer need them because you are sure (you have a proof of it) that the integer 0 with the meaning Apple with never be used with another meaning.