Generic printer for OCaml values
This ppx rewriters add support for the
points which do exactly what you expect:
$ [%show] (1, 2, Some 'c');; - : string = "(1, 2, Some 'c')" $ Format.printf "%a@." [%pp] (1, 2, Some 'c');; (1, 2, Some 'c') - : unit = ()
And to save a few characters you can also do this:
external show : _ -> string = "%show" external pp : Format.formatter -> _ -> unit = "%pp"
The code is based on a old compiler path available here.
I wouldn't recommend using this in production code, but it is really useful for quick debugging.
Building and Running
- This will create a
ocamlc -ppx ./ppx_show.native example/example.ml
How does it work?
ppx_show uses the OCaml typer to find the type inferred for the
pp and generates a function according to this
It has heuristics to print some abstract types such as sets and maps
Tricks for abstract types
There are two ways to automatically print abstract types:
- reveal them as private:
type t = private <internal representation>
- declare a specially named function that ppx_show will recognize
For (2) the function must be named as follow:
The implementation can be as simple as:
let pp_print_t : _ -> t -> _ = [%pp]
- only works with OCaml 4.03
- to use in code that requires
-rectypes, you need to pass
-rectypesto the ppx rewriter as well