Search code examples
ocamlprintfpretty-print

user-defined printer in OCaml


printf, fprintf, etc. : all accept the %a conversion.

The manual says for %a:

"user-defined printer. Takes two arguments and apply the first one to outchan (the current output channel) and to the second argument. The first argument must therefore have type out_channel -> 'b -> unit and the second 'b. The output produced by the function is therefore inserted in the output of fprintf at the current point."

I can't understand what a user-defined printer is for, and how you would implement and use it. Can someone explain the motivation and maybe provide an example?

For example, when you want to, say, print a complex data-structure, why is it not possible to just print the data-structure with a custom function directly to a string or to output?


Solution

  • If you have a function ty -> string you can use it with "%s" to print your data, so I think in realistic cases you can "just print your data structure". It might be a stylistic choice to use "%a" instead. It does seem more consistent in some ways.

    On a 32-bit system, strings are limited to around 16MB in length. So you could imagine a case where the "%a" would work while "%s" would fail: if the intermediate string is longer than this. I've never had this come up in practice, though. I just use "%s", myself.