Search code examples
ocamlpretty-print

OCaml : how to install pretty printer and use it in the code?


In the OCaml's top-level and debugger one can register a pretty printer via install_printer printer-name. Is there any way to achieve the same, but in the OCaml code ? More concretely, I need a logging facility that does not require to explicitly specify a pretty-printer for each invocation of log. That is, something like:

(* First, user sets a global pretty-printer for a type *) 
let pp_foo : Foo -> string = ...
let () = Logging.register pp_foo
...
(* Then it can be used like that *)
let foo : Foo = ...
let () = Logging.log foo

Solution

  • Not to contradict to what Octachron is saying, but it is actually possible to get some dumping facility, that will be that polymorphic. It would be fragile, and indeed won't differentiate between [], 0, None, but will work pretty fine with OCaml builtin types. Such function could be found in various libraries with different modifications, for example, Extlib and Batteries libraries provide one under the dump name, here is an example of toplevel interaction with it:

    # #use "topfind";;
    # #require "extlib";;
    # Std.dump;;
    - : 'a -> string = <fun>
    # Std.dump ["hello"; "world"];;
    - : string = "[\"hello\"; \"world\"]"
    # Std.dump [];;
    - : string = "0"
    # Std.dump None;;
    - : string = "0"
    # Std.dump [|"hello"|];;
    - : string = "(\"hello\")"
    # module Abstract : sig type t val x : t end = 
       struct type t = string list let x = ["hello, world"] end;;
    module Abstract : sig type t val x : t end
    # Std.dump Abstract.x;;
    - : string = "[\"hello, world\"]"
    # 
    

    With all that power at your hands, I would still suggest you use it only for the debugging purposes.

    Finally, if you're curious how the toplevel pretty printing works, here is the answer. In fact, it relies on the typing environment, which is available for the toplevel, which is in part an interpreter and in part a compiler. This pretty printing facility is still rather fragile.