Take the 2-minute tour ×

In ocaml, let's say we have:

type t = A of int | B of string
let x = [A 5; B "y"]

Then, we can iterate the list, and use match statement to decide what to do with A or B.

In java, we could have:

ArrayList<Object> x = new ArrayList<Object>();
x.add(new Integer(5));

On the array list iteration, we would have to instanceof and downcast to work with data.

Is it true that, internally, ocaml carries runtime type information as java, and the type matching statement works like java instanceof-downcast, but type is safe because there's no way one can write

if (element instanceof Integer) {
  String e = (String) element;
share|improve this question
I am not 100% sure that what is problem you are facing? In above code, moreover you can do String e = element + "";. –  Ravi A Jan 31 '13 at 7:44
I heard it before that ocaml does not carry rtti, I wondered how the matching would know. As with jmg's explanation, they call it _ constructor _ which is the minimal info needed in runtime, instead of carrying the whole type info. –  romerun Jan 31 '13 at 8:31

2 Answers 2

up vote 2 down vote accepted

No and Yes. In general OCaml does not carry any runtime type information for every value around (As was already said in Jeffrey's answer). And that is safe because of the design of the type system as a completely static type system. A and B are not types in OCaml, they are constructors. And constructors are distinguishable at runtime. But only between constructors of one type. So, the OCaml compiler represents only the bare minimum at runtime, that is necessary to implement pattern matching.

share|improve this answer

No, OCaml doesn't carry any runtime type information (to speak of). There's no downcasting going on because the types don't participate in a subtype relationship. (For types that do participate in subtyping, OCaml doesn't allow downcasting.) Yes, the code is safe because the language is carefully defined so that the safety can be checked at compile time.

share|improve this answer

Your Answer


