Course map
Haskell // 11

Type classes

Read

Classes and instances

A type class names a set of functions that many types can support. Show is the class of types that can be turned into a String; Eq of types that can be compared with ==; Ord adds < and compare.

data Color = Red | Green | Blue

instance Show Color where
  show Red   = "red"
  show Green = "green"
  show Blue  = "blue"

instance Eq Color where
  Red   == Red   = True
  Green == Green = True
  Blue  == Blue  = True
  _     == _     = False

An instance says how a particular type implements the class. Usually deriving (Show, Eq, Ord) writes the obvious instance for you; write it by hand when you want something different, like the lower-case names above.

01 / 05