typestar

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

  1. data Priority = Low | Normal | High | Urgent gains five instances from one deriving (Show, Eq, Ord, Enum, Bounded) clause.
  2. everyPriority spans the whole type as [minBound .. maxBound], taking the ends from Bounded and the walk from Enum.
  3. filter (> Normal) leans on the derived Ord, and ticketWeight = fromEnum numbers the constructors from zero.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Typeclasses, step 19 of 27 in Language basics.

← Previous Next →