Printf vs. Format?

I know there are projects like Fmt and ppx derivers that simplify the generation of pretty printers for OCaml objects, but in the general interest of knowing things, today I’m trying to discover the Stdlib way of doing such things.

I am generally familiar with the Printf module and use it happily. Today, I looked more deeply into the Format module and I discover that it is more or less the same thing, but with a lot of extra boxes and breaks. Seems a little over-complicated, but I’m sure all these “boxes” are useful when you need them, and these features seem to be opt-in.

I also discoverd "%a" today, and this is a very good discovery. It seems have a similar—but not exactly the same—meaning within the contexts of Printf and Format.

So my general observation is this:

  • Printf and Format are two libraries that do almost the same thing in almost the same way, but are nonetheless incompatible for most purposes.

I have several questions:

  • Is this observation correct?
  • If so, is there a compatibility shim between Printf and Format?
  • What is the preferred way to create pretty printers for my own types? I’ve been using Printf happily for a a while, but the more I look into it, the more it seems like this is not the “blessed” path; i.e. that pp functions should be created in terms of Format.

And a side thingy: how do I plug my pretty printers into the toplevel/utop?

1 Like

Not quite: Printf is an output library similar in scope to the IO of the standard C library, its main feature is the support for “formatting strings” which contain placeholders which can be replaced by the textual representation of various arguments. Format, on the other hand, is a pretty-printing library: it will introduce line breaks and indentation to make sure that your output looks “nice” (the exact line breaks and indentation introduced depends on the hints specified by using “boxes”). In other words, one can easily use Format in place of Printf (simply by not introducing any boxing annotations), but not the other way around.

To learn more about Format:

May also be of interest:



Use the #install_printer utop pragma.