2

Haskell's ghci can print nicely any value belonging to a type that implements Show typeclass. Is there any equivalent in OCaml that lets utop automatically print values of user-defined types nicely? Typing x |> M.to_string every line is quite tedious…

Sventimir
  • 1,996
  • 3
  • 14
  • 25

1 Answers1

2

In your module for your type M.t define the function:

val pp : Format.formatter -> t -> unit

You can then install a printer for the type in ocaml or utop using:

# #install_printer M.pp

See the toplevel directive section of the manual.

Daniel Bünzli
  • 5,119
  • 20
  • 21
  • That seems to work for me, but how can I use this `Format.formatter` value in this function. When I wrote naively: `let pp _ r = to_string r |> print_string`, I got output before type signature instead of after `=`. The Format module documentation does not help me much… – Sventimir Jul 21 '17 at 19:51
  • Okay, I've found it on my own: there's `val pp_print_text : formatter -> string -> unit` function in `Format` module which does exactly what's expected. Thanks a lot! – Sventimir Jul 22 '17 at 08:58
  • Just one comment about your first try. You cannot do that you need to hook in the format system abstraction you cannot just print output by your own in pretty printing functions. – Daniel Bünzli Jul 24 '17 at 12:17