Felix
Felix

Reputation: 8505

How to override/provide custom instances using bs-deriving

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?

Upvotes: 1

Views: 42

Answers (1)

glennsl
glennsl

Reputation: 29136

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.

Upvotes: 1

Related Questions