Skip to content
Generic printer for OCaml
OCaml Other
  1. OCaml 98.9%
  2. Other 1.1%
Branch: master
Clone or download
diml Merge pull request #4 from hbbio/master
fix for OCaml 4.04.0
Latest commit f9779b3 Dec 19, 2016
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
example support maps and sets Nov 27, 2015
src fix for OCaml 4.04 Dec 18, 2016
.gitignore added gitignore Nov 27, 2015
LICENSE added license Nov 27, 2015
Makefile added example Nov 27, 2015
README.md Add build and run instructions to README.md Aug 10, 2016
_tags small fixes Nov 27, 2015
myocamlbuild.ml added license Nov 27, 2015

README.md

Generic printer for OCaml values

This ppx rewriters add support for the [%show] and [%pp] extension 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

  1. Run make inside the ppx_show directory
  2. This will create a ppx_show.native file.
  3. Run: 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 argument of show or pp and generates a function according to this type.

It has heuristics to print some abstract types such as sets and maps obtained from Set.Make and Map.Make.

Tricks for abstract types

There are two ways to automatically print abstract types:

  1. reveal them as private: type t = private <internal representation>
  2. declare a specially named function that ppx_show will recognize

For (2) the function must be named as follow:

  • string_of_<type-name> for [%show]
  • pp_print_<type_name> for [%pp]

The implementation can be as simple as:

let pp_print_t : _ -> t -> _ = [%pp]

Limitations

  • only works with OCaml 4.03
  • to use in code that requires -rectypes, you need to pass -rectypes to the ppx rewriter as well
You can’t perform that action at this time.