1

Using bs-deriving, I can derive e.g. show instances using [@deriving show]. However, it's not clear how I would use the same derivation but providing a custom show instance for a specific datatype.

Example:

[@deriving show]
type bar = |Bar(int);

[@deriving show]
type foo = |Foo(int, bar);

Using the above example, how would I change Bar to print its integer in e.g. hexadecimal?

glennsl
  • 28,186
  • 12
  • 57
  • 75
Felix
  • 8,385
  • 10
  • 40
  • 59
  • I think that's a bit too advanced for the simple BuckleScript implementation, although you could try using `@printer` like in [ppx_deriving](https://github.com/ocaml-ppx/ppx_deriving#plugin-show). – glennsl Apr 19 '20 at 15:53
  • What do you mean about "the simple bucklescript implementation"? Is there something else I could be using? – Felix Apr 19 '20 at 17:14
  • Oh sorry, BuckleScript comes with [its own simplified deriving mechanism](https://bucklescript.github.io/docs/en/generate-converters-accessors), but that's not what you're talking about. `bs-deriving` seem to be a port of ppx_deriving, so `@printer` should work there too. I'll write an answer... – glennsl Apr 19 '20 at 18:00

1 Answers1

1

You should be able to use @printer to define your own printer function like this:

[@deriving show]
type bar = Bar([@printer fmt => fprintf(fmt, "0x%x")] int);

fprintf is a locally defined function which takes a formatter, a format string and a number of values as specified by the format string. For brevity in this case we partially apply it to avoid having to explicitly pass the int value. It's equivalent to (fmt, n) => fprintf(fmt, "0x%x", n).

The format string specifies that the number should be formatted as hexadecimal with lowercase letters (the %x part) and prefixed with 0x. So 31 would output 0x1f.

glennsl
  • 28,186
  • 12
  • 57
  • 75