Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml - polymorphic print and type losing

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?

like image 354
demi Avatar asked Sep 16 '11 09:09

demi


1 Answers

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.

like image 87
camlspotter Avatar answered Sep 21 '22 20:09

camlspotter