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));
x.add("y");
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;
}
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.