Deriving show not working as expected

I’m a little confused on how ppx_deriving.show works. I’m pretty new to OCaml so I might be getting something wrong, but I haven’t been able to figure this out on my own yet.

I have the following code in deriver.ml:

type simple =
    { ok: bool; } [@@deriving show]

let s =
  { ok = true; }
let p =
  print_endline (show s)

and the following dune file:

(executable
 (name deriver)
 (preprocess
  (pps ppx_deriving.show)))

Now when I run dune build I’ll get the error message Error: Unbound value show which is suprising since, having worked with Haskell and Rust, I expected @@deriving would provide this function automatically.

What am I missing here?

2 Likes

Hi @mradke. Welcome to OCaml!

The derived show function for a type called simple will be show_simple. PPX derivers in OCaml generally have a convention that the type name appears in the names of generated functions unless the type is called t (in which case the name is generally omitted). So:

type t = ... [@@deriving show]
val show : t -> string

type foo = ... [@@deriving show]
val show_foo : t -> string

This helps ensure that the generated functions for different types don’t shadow each other.

For debugging these sorts of problems it’s very helpful to have some way to inspect the generated code. In my own editor environment, I tend to do this by putting the code with [@@deriving] inside a wrapper module and then querying the type of that module. If you’re using something like VS Code then I’d guess there is a nicer solution than this by now :slight_smile: One can also use a script like this: Simple script for expanding OCaml PPXes (in a readable way) · GitHub.

Hope this helps!

Craig.

6 Likes

Thank you so much. :heart:
However my SSCCE was unfortunately neither complete, nor correct, I’m afraid… :see_no_evil:

What I ommitted was that I use a project layout where I import a library in which the deriving takes place. So I wondered why this isn’t working with my imported module?

It turns out that one also needs to specify the ppx_deriving.show inside the libraries dune file, like so:

(library
 (name my_lib)
 (preprocess
  (pps ppx_deriving.show))) ; I omitted this

Now, if you have your type simple in a file called mymodule.ml you can call it from main.ml like so: print_endline (Mymodule.show_simple s).

Thanks again for the pointer! :slight_smile:

1 Like