开发者

Ocaml - polymorphic print and type losing

开发者 https://www.devze.com 2023-04-05 20:24 出处:网络
There is series of functions like print_int, print_endline and Printf in OCaml. I can\'t do something like:

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 does开发者_如何学JAVAn'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.

0

精彩评论

暂无评论...
验证码 换一张
取 消