Are there any easy-to-use tool for generic programming in OCaml?

If I have some ADTs

type 'a t1 = A of 'a
type 'b t2 = B of 'b

and I need a map function, I have to write similar code twice:

let map_t1 : ('a -> 'b) -> 'a t1 -> 'b t1 = fun f (A x) -> A (f x)
let map_t2 : ('a -> 'b) -> 'a t2 -> 'b t2 = fun f (B x) -> B (f x)

When I write map_t1 and map_t1 by hand, my mind runs the same algorithm that can be reused to write a map function for any other ADT.

There are other functions that have a wide appeal for ADTs, such as:

  • show : print an ADT value to string
  • fold : systematically replace ADT constructors in-place by some functions

Does OCaml has a package to generate these functions automatically? I am imagining a tool with a GUI that has a text area into which I can copy a type definition, then the tool generates a list of useful functions (map, show, fold, etc.) that I may need, and I can just copy and paste the needed ones into my code.

Haskell seems to have type classes and deriving keyword , but type class instances still need to be hand-coded.

You’re looking for ppx_deriving. Usage would look like so for the map “plugin”:

type 'a t1 = A of 'a
[@@deriving map]

…which gives you a map_t1 function, just as you wrote manually.

There are likewise other plugins for show, fold, and a bunch of other related utilities; ppx_deriving also provides a way for others to independently develop plugins, such as ppx_deriving_yojson, which generates functions for encoding and decoding values of a given type to and from JSON.