Printf @@deriving sexp

For a type t with @@deriving sexp is there a simple way to print x:t via printf ?

EDIT: I’m basically looking for Rust’s #[deriving(Show)]

There is @@deriving show ppx that generates val pp: Format.formatter -> 'a -> unit that can be combined with Format.printf.

1 Like

If you want to print S-expressions directly, you can use a combination of Sexp.pp and converting to sexp.

Give me a sec, let me dig up an example.

Yeah, Sexp.to_string Data Serialization with S-Expressions - Real World OCaml

You can avoid going to string as an intermediary if you use the pp functions:

open Core

type data = Leaf of int | Node of data list
[@@deriving sexp]

type t = {
  my_int: int;
  my_float: float;
  my_data: data
} [@@deriving sexp]


let instance = {my_int=1; my_float=1.0; my_data=Leaf 0}

let () = Format.printf "%a" Sexp.pp_hum ([%sexp_of: t] instance)
(* outputs: ((my_int 1) (my_float 1) (my_data (Leaf 0))) *)
3 Likes

If you’re using the right Jane Street ppxes (ppx_jane will include them), you can do this:

let () = printf !"Foo: %{sexp:Foo.t} and Bar: %{Bar}\n" foo bar

if Foo.sexp_of_t and Bar.to_string are defined (note the ! before the format string).

Other options are

let () = print_s [%message "Foo:" (foo: Foo.t)]

or

let () = print_s ([%sexp_of: Foo.t] foo)
3 Likes

Wow, I wasn’t aware of all this functionality. Would anyone be willing to update the debugging tutorial with a section(s) about printf debugging, native code tracing, ppx_debug?

1 Like

Ah, yes, forgot to mention earlier, but alongside these, @dariusf also has GitHub - dariusf/ppx_interact: Interactive breakpoints!, which provides Python-style interactive breakpoints by compiling a toploop into the program:

let () =
  let xs = [1; 2; 3] in
  let f (a : int) =
    [%interact]
  in
  print_endline "hello!";
  f 2;
  print_endline "goodbye!"

It’s only implemented for bytecode, but I can’t see why it couldn’t also be ported to native code as well.

2 Likes