Deriving
1. Deriving
What the cool thing that Deriving does is actually automaticlly implementing instance for particular type class.
For instance, a Person derives Eq
data Person = Person │ { firstName :: String │ , lastName :: String │ , age :: Int │ } │ deriving Eq
Then we are able to compare two Persons because Haskell make the type Person to be a instance of typeclass Eq.
Take another example,
data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday │ │ │ deriving (Bounded, Enum)
The Bounded typeclass defines things that have lowest possible value
and highest possible value. The Enum typeclass defines things that
have predecessors and successors.
Let’s read one of function in Bounded typeclass minBound, which just
return something that is instance of Bounded.
minBound :: (Bounded a) => a
Hence, if enforce its return type to be Day, we will get result
ghci> minBound :: Day Monday
Take a look at one function of Enum typeclass
succ :: (Enum a) => a -> a
We could easy guess the result of succ Tuesday will be Wednesday.
2. Further study
- How does the Deriving being implemented in Haskell?
Thanks a guy point me I could go further by study Data.Derive at the beginner mailing session.