Say I have my own data structure, as a silly example,
type 'a mylist = Empty | Cons of 'a * ('a mylist)
.
I would like the toplevel to print this list in the form {a,b,...}
. Here a
, b
of type 'a
are printed according to a printing function installed in the toplevel with #install_printer, or if none is available, as <abstr>
.
I know how I would define a printing function for a monomorphic mylist, but is there a polymorphic way to tell the toplevel to just put {
, ,
and }
and use what it already knows for any type that comes in between?
I don't think it's possible. The reason is that OCaml throws away types at run time and therefore it is not possible to have a function which behave differently depending on a type at runtime. So you can't define such a polymorphic printing function. Note that #install_printer
is not part of the OCaml language but it a directive for the toplevel, which still knows about type. The only possible solution is to define a generic printing function which take the 'a
printing function as parameter. Something like
'a -> string -> 'a mylist -> unit
But I think you already know that, don't you ?
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