Deriving instances in Haskell
A deriving clause on a sum type supplies Show, Eq, Ord, Enum, and Bounded for free.
module Priorities where
-- One deriving clause hands you five instances at once.
data Priority = Low | Normal | High | Urgent
deriving (Show, Eq, Ord, Enum, Bounded)
-- Bounded supplies the endpoints; Enum walks the range between them.
everyPriority :: [Priority]
everyPriority = [minBound .. maxBound]
-- Ord ranks constructors in declaration order, so Urgent is the largest.
needsPaging :: [Priority]
needsPaging = filter (> Normal) everyPriority
-- Enum numbers the constructors from zero upward.
ticketWeight :: Priority -> Int
ticketWeight = fromEnum
How it works
data Priority = Low | Normal | High | Urgentgains five instances from onederiving (Show, Eq, Ord, Enum, Bounded)clause.everyPriorityspans the whole type as[minBound .. maxBound], taking the ends from Bounded and the walk from Enum.filter (> Normal)leans on the derived Ord, andticketWeight = fromEnumnumbers the constructors from zero.
Keywords and builtins used here
BoundedEnumEqHighIntLowNormalOrdPriorityShowUrgentdataderivingeveryPrioritymoduleneedsPagingticketWeightwhere
The run, in numbers
- Lines
- 17
- Characters to type
- 559
- Tokens
- 62
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 50 seconds.
Step 1 of 3 in Typeclasses, step 19 of 27 in Language basics.