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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With