Haskell GHC Generics Idea
GHC Generics is a way to describe a type's shape so one function can work for many types. Deriving Generic gives a type a representation that generic functions can read.
A round trip returns the same value
From turns Box 5 into its representation. To turns it back, and the equality check proves it.
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics (Generic, from, to)
data Box a = Box a deriving (Show, Eq, Generic)
main :: IO ()
main = print (to (from (Box 5)) == Box 5)The same round trip works for two fields
A two-field value travels the same road. The equality check proves it returns unchanged.
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics (Generic, from, to)
data Pair a b = Pair a b deriving (Show, Eq, Generic)
main :: IO ()
main = print (to (from (Pair 3 "hi")) == Pair 3 "hi")The round trip works for other field types
Changing the field type changes nothing about the trip. The check still prints True.
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics (Generic, from, to)
data Box a = Box a deriving (Show, Eq, Generic)
main :: IO ()
main = print (to (from (Box "hi")) == Box "hi")Example
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics (Generic, from, to)
data Box a = Box a deriving (Show, Eq, Generic)
data Pair a b = Pair a b deriving (Show, Eq, Generic)
main :: IO ()
main = do print (to (from (Box 5)) == Box 5); print (to (from (Pair 3 "hi")) == Pair 3 "hi")Key points
- Generic: a class that gives a type a shape representation.
- Representation: a type-level picture of a type's constructors and fields.
- From: the function that turns a value into its representation.
- To: the function that turns a representation back into a value.
- Round trip: going from a value to its representation and back again.
In this example, Box and Pair both derive Generic, from turns each value into its representation, and to turns each representation back so the two equality checks both print True.
Note
a representation value is never printed, because its form is nested noise.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does to (from x) check?