Deriving in Haskell

June 14, 2011, Tags: typeclass, deriving, haskell


What the cool thing that Deriving does is actually automaticlly implementing instance for perticular 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  

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.

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.