Search code examples
ocamltostringpretty-print

Use a pretty printer to write a to_string function


I have defined a big pretty printer pp: out_channel -> t -> unit over a big type t. Therefore, I can use it like Printf.fprintf stdout "%a" x where x: t, or chain printing like Printf.fprintf chan "%a" pp x where chan: out_channel.

Now I need to convert what is printed to a string or a text. Does anyone know if there is a way to leverage/use the function pp rather than writing a function to_string: t -> unit from scratch?


Solution

  • Format.asprintf should suit your needs, if you pp is implemented for Format.formatter type instead of out_channel. The Format.formatter is a more general type and should be preferred to the concrete out_channel. In fact, a sort of a standard type for pretty printer is the Format.formatter -> 'a -> unit type, at least it is required by the #install_printer directive in OCaml toplevel, debugger and other facilities. Functions of the same type are used in Core library to implement Pretty_printer interface.

    So, if you will reimplement your pp function to work with the Format module (usually for this it would be enough just to open Format module), then you can reuse it. The functions, that print to out_channel module can't be retargetered to print into string. So it is better not to write them.