For OCaml, is there a way to print arbitrary data, or do I need to write a custom printer for every object?
In Rust, I can do something like
#[derive(Deubg)]
struct ...
and then it will auto derive a way to print the data for me.
In Clojure, most objects can be printed as is.
In OCaml, is there a way to print objects without writing a custom printer function?
There exist some deriving mechanisms in OCaml quite similar to those you know in Rust (or Haskell): they are implemented by PPX syntax extensions, namely ppxlib
or ppx_deriving
. With such extensions, you may write for instance:
type example = A | B [@@deriving show]
and two functions pp_example : Formatter.formatter -> example -> unit
and show_example : example -> string
will be automatically generated next to the type declaration. (show
comes as a standard plugin with ppx_deriving
; if you prefer to use ppxlib
, you will need an additional plugin for show
: you may use my ppx_show
plugin.)
3 Likes
You may have seen “genprint” announced just today; it’s also a way to print arbitrary values, via a different pathway.