printing polymorphic containers in ocaml toplevel
Asked Answered
L

1

7

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?

Leis answered 9/3, 2014 at 11:45 Comment(1)
I don't think this is possible, but it's a great question. I'd love to learn otherwise.Thickset
A
1

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 ?

Amadeus answered 13/3, 2014 at 23:2 Comment(2)
actually, no i did not. this sounds like it would solve the practical problem, or doesn't it? the types that are relevant are all in their own module, like M.t, and have a function M.print of type M.t -> string. (and M is M1, M2, ...). so then i would need to make a functor Mylist(M) that makes an M.t mylist (parametrized by M) and then gets its own print function derived from M.print (?) this sounds a bit heavy, though and i am not sure how to make it fall back to <abstr> for an unknown type instead of M.t.Leis
accepting since there seems to be no positive answerLeis

© 2022 - 2024 — McMap. All rights reserved.