12
votes

There is series of functions like print_int, print_endline and Printf in OCaml. I can't do something like:

let n = 10 in
print n;; (* And I haven't to change `print` in case type of `n` changed *)

That is polymorphic print like in Java, C#, Python and others. Instead, we have C-like with type explicitly defined by programmer. So I think that OCaml losing type information during compilation and doesn't have it at runtime, right? And this is the reason why we need mli files also?

EDIT: I'm tired to write function like *print_listi*, *print_list_tuple2i* and so on. How can I do it better?

1
Well there's the Printf module and all the stuff that goes with it. At least it's an improvement and is somewhat type safe. I don't do enough ocaml to know if there's any other builtin alternatives.Jeff Mercado

1 Answers

22
votes

You are right: OCaml throws away types at run time and therefore no way to distinguish your 10 is really an int or 10th 0-ary variant constructor. Constructor names are neither available, so it is impossible to print data.

Moreover, OCaml's polymorphism is parametric. You cannot define functions that work differently depending on types.

One partial workaround of this is to use CamlP4 to auto-generate printer functions for data types. But still, you cannot have " polymagical" print which works for everything. You have to combine printers by hand, like print_list (print_option print_int).

I have extended OCaml to have such polymorphic print (and other nice things) years ago. It's called GCaml. But not maintained for long.

mli files do not relate to this. They are for writing module signatures, for hiding implementations for simpler interfaces for module users.