Introduction to GHC.Generics

2018-05-11
haskellgenerics

Generic functions traverse the structure of a type to produce the body of a function with the goal of reducing code reptition.

Imagine a simple record type and a function that converts any type to a String.

Here is a simplified version of how we traverse over the structure of the data type to produce the body of the genericShow function. The following is pseudo code and does not actually compile. It intends to emulate the way GHC.Generics works in a simple, readable manner.

Examples of Generic Representations

Product (Record with Fields)

Sum Type without Values

Sum Type with One Value

Sum Type with Multiple Constructors and Type Parameters

GHC.Generic Types

We can view use our simple representation as type synonyms for the real types in GHC.Generics.

GHC.Generic Representations

Now we will take a look at the real generic repsentations of the types from above. In GHCi, you can see the representations by calling :kind! Rep on any type that derives Generic

Product (Record with Fields)

Sum Type without Values

Sum Type with One Value

Sum Type with Multiple Constructors and Type Parameters

You can also see the generic representations when you build the package: stack build --ghc-options=-ddump-deriv.