Haskell Language Type Classes Type class inheritance: Ord type class


Example

Haskell supports a notion of class extension. For example, the class Ord inherits all of the operations in Eq, but in addition has a compare function that returns an Ordering between values. Ord may also contain the common order comparison operators, as well as a min method and a max method.

The => notation has the same meaning as it does in a function signature and requires type a to implement Eq, in order to implement Ord.

data Ordering = EQ | LT | GT

class Eq a => Ord a where
    compare :: Ord a => a -> a -> Ordering
    (<)     :: Ord a => a -> a -> Bool
    (<=)    :: Ord a => a -> a -> Bool
    (>)     :: Ord a => a -> a -> Bool
    (>=)    :: Ord a => a -> a -> Bool
    min     :: Ord a => a -> a -> a
    max     :: Ord a => a -> a -> a

All of the methods following compare can be derived from it in a number of ways:

x < y   = compare x y == LT
x <= y  = x < y || x == y -- Note the use of (==) inherited from Eq
x > y   = not (x <= y)
x >= y  = not (x < y)

min x y = case compare x y of
               EQ -> x
               LT -> x
               GT -> y

max x y = case compare x y of
               EQ -> x
               LT -> y
               GT -> x

Type classes that themselves extend Ord must implement at least either the compare method or the (<=) method themselves, which builds up the directed inheritance lattice.