Printing polymorphic containers in ocaml toplevel

Let's say I have my own data structure, as a stupid example, type 'a mylist = Empty | Cons of 'a * ('a mylist) type 'a mylist = Empty | Cons of 'a * ('a mylist) .

I would like theplevel to print this list in the form {a,b,...} . Here a , b type 'a are printed according to the print function set at the top level with #install_printer, or if it is not, as <abstr> .

I know how I would define a print function for a monomorphic mylist, but is there a polymorphic way to tell Tofulev to simply put { and } and use what he already knows for any type of what happens between them?

+6
source share
1 answer

I do not think that's possible. The reason is that OCaml throws types at runtime, and therefore it is not possible to have a function that behaves differently depending on the type at runtime. Therefore, you cannot define such a polymorphic print function. Note that #install_printer not part of the OCaml language, but is a top-level directive that still knows about the type. The only possible solution is to define a common print function that performs the print function of 'a as a parameter. Sort of

 'a -> string -> 'a mylist -> unit 

But I think you already know that, right?

+1
source

All Articles