Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing polymorphic containers in ocaml toplevel

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?

like image 380
user3240588 Avatar asked Mar 09 '14 11:03

user3240588


1 Answers

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 ?

like image 90
hivert Avatar answered Oct 08 '22 16:10

hivert