You may also use the ppx_deriving.show plugin from the ppx_deriving library. This plugin is able to generate 'a -> string
and Format.formatter -> 'a -> unit
(where 'a
is the type you want to print) functions which can then be used for value printing.
type t =
{ number : int
; text : string
}[@@deriving show]
This will produce show
and pp
functions of type t -> string
and Format.formatter -> t -> unit
, which can then be used as
let v = { number = 2; text = "Hello world"} in
print_endline (show v)
or
let v = { number = 2; text = "Hello world"} in
let s = Format.asprintf "%a" pp v in
print_endline s
Of course, you can always define such functions for the needed types by yourself.
As I can see, almost every library introducing a new type also provides pretty-printing (kinda pp
in this example) functions out of the box.