mpl icon indicating copy to clipboard operation
mpl copied to clipboard

be able to print any type

Open acarumut opened this issue 3 years ago • 6 comments

it is a pain to have to write print functions i have encountered a good example (simplifying here to make the point)

i was writing a function

fun f (x: 'a datastructure): 'a datastructure = 
... 
bunch of code

now i am testing with 'a = int but if i try to print x inside f, then i break polymorphism because i am assuming int :( so basically i have to change my type signature etc...

acarumut avatar Oct 05 '22 15:10 acarumut

Yeah this would be fantastic to have. Conceptually it seems straightforward for the compiler to provide a polymorphic primitive toString: 'a -> string. We could elaborate it into real code immediately after monomorphization.

Generating pretty printers automatically for arbitrary types seems like it could be a pain! Perhaps we could start with simple things (e.g. just base types, integers, tuples, etc.) and extend it incrementally with support for more interesting stuff.

shwestrick avatar Oct 10 '22 17:10 shwestrick

would it be feasible to extend the compiler with an "anytime" expression that gets passed through the various stages of the compilation? if so, then this and similar things could be easy to implement perhaps? (this feature would be used only by the compiler, so we would not expose it to the user.)

umutacar avatar Oct 11 '22 13:10 umutacar

Yeah, MLton/MPL essentially already have these! MLton calls them "primitive" operations. Primitives can pass through all compilation stages if needed, and different primitives are eliminated (i.e., implemented) by different passes.

shwestrick avatar Oct 11 '22 13:10 shwestrick

maybe we need a to_string primitive?

umutacar avatar Oct 11 '22 13:10 umutacar

Yup! That's what I was imagining above. The primitive can then be eliminated (elaborated into real code) at any point after the monomorphization pass.

shwestrick avatar Oct 11 '22 14:10 shwestrick

cool!

acarumut avatar Oct 11 '22 14:10 acarumut