Rep
is a type familyGHC Generics are all about taking user defined types of which there are infinitely many,
and converting them into a combination of a small number of primitive types.
If that sounds a bit like a function to you then you’re spot on.
The name of the function that performs this conversion is Rep
,
and it takes and returns types instead of regular values.
A function on types is sometimes called a type family.
To understand Rep
let’s first look at a ‘regular’ Haskell function.
Haskell allows us to define functions using multiple definitions, like so:
isEven :: Word -> Bool
isEven 0 = True
isEven n = not (isEven (n - 1))
We can define a type family in a similar fashion.
{-# LANGUAGE TypeFamilies #-}
data Yep
data Nope
type family HasManyValues a
type instance HasManyValues () = Nope
type instance HasManyValues Bool = Nope
type instance HasManyValues Int = Yep
type instance HasManyValues (Maybe n) = HasManyValues n
Rep
is very similar to HasManyValues
.
It also takes a single argument (an original type) and returns another type (the generic representation).
We can manually write a line type instance Rep MyType
if we want,
but will usually let GHC do it for us by adding deriving (Generic)
to a type.