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 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.