TExcelTAD
Home › Haskell › Haskell Type Classes Basics

Haskell Type Classes Basics

How can == compare numbers and strings, and show print booleans and lists? The answer is type classes. A type class is a named set of operations, such as "can be compared for equality". A type that provides those operations is an instance of the class. Functions can then require "any type that is an instance of X".

haskell · try it yourself
main :: IO ()
main = do
  print (3 == 3, "abc" == "abd", [True] == [True])
  print (5 < 7, "apple" < "banana", 'z' > 'a')
  print (show 3.5, show [1, 2], show (Just 'x'))
(True,False,True)
(True,True,True)
("3.5","[1,2]","Just 'x'")

Reading constraints

Ask GHCi for the type of == and you see a class constraint before the =>:

text
ghci> :type (==)
(==) :: Eq a => a -> a -> Bool
ghci> :type elem
elem :: (Foldable t, Eq a) => a -> t a -> Bool
ghci> :type (+)
(+) :: Num a => a -> a -> a

Read Eq a => a -> a -> Bool as: "for any type a that is an instance of Eq, take two as and return a Bool". Both arguments must have the same type, so 3 == "3" does not compile.

You can write constraints in your own signatures. This function works for every type whose values can be ordered:

haskell · try it yourself
largestOfThree :: Ord a => a -> a -> a -> a
largestOfThree x y z = max x (max y z)

isMember :: Eq a => a -> [a] -> Bool
isMember _ [] = False
isMember x (y : ys) = x == y || isMember x ys

main :: IO ()
main = do
  print (largestOfThree 3 9 4)
  print (largestOfThree "kiwi" "fig" "plum")
  print (isMember 'q' "haskell", isMember 7 [1, 7, 9])
9
"plum"
(False,True)

The standard classes

Class Operations Instances include
Eq ==, /= almost every type (not functions)
Ord <, <=, >, >=, compare, max, min numbers, Char, String, lists and tuples of Ord types
Show show almost every type; used by print
Read read numbers, Bool, Char, lists, tuples
Enum succ, pred, [a .. b] ranges Int, Char, Bool, Ordering
Bounded minBound, maxBound Int, Char, Bool
Num +, -, *, abs, negate, fromInteger Int, Integer, Double
Integral div, mod, toInteger Int, Integer
Fractional /, recip Double, Float, Rational
Floating sqrt, exp, sin, **, pi Double, Float

Classes form a hierarchy: every Ord type is also Eq (you need equality to have ordering), and every Integral or Fractional type is also Num.

Enum and Bounded

haskell · try it yourself
main :: IO ()
main = do
  print (succ 'a', pred 10)
  print [LT ..]
  print (fromEnum 'A', toEnum 66 :: Char)
  print (minBound :: Bool, maxBound :: Char)
  print ([minBound .. maxBound] :: [Bool])
('b',9)
[LT,EQ,GT]
(65,'B')
(False,'\1114111')
[False,True]

Ranges such as ['a' .. 'e'] work because Char is an Enum. Any type with an Enum instance gets range syntax for free, including the types you define yourself.

The numeric classes in practice

Number literals are polymorphic: 5 can be any Num type, 2.5 any Fractional type. This is why some combinations need a conversion:

haskell · try it yourself
halve :: Fractional a => a -> a
halve x = x / 2

countHalf :: [b] -> Double
countHalf xs = halve (fromIntegral (length xs))

main :: IO ()
main = do
  print (halve 9)                 -- 9 is used as a Double
  print (halve (1.5 :: Float))
  print (countHalf "abcde")
  print (sqrt 2 * pi)
4.5
0.75
2.5
4.442882938158366
Conversion From → to
fromIntegral any Integral (Int, Integer) → any Num
realToFrac Double/Float → another fractional type
round, floor, ceiling, truncate fractional → integral
toInteger Int → Integer

Deriving instances for your own types

For your own data types, GHC can write the standard instances for you with a deriving clause:

haskell · try it yourself
data Size = Small | Medium | Large
  deriving (Show, Eq, Ord, Enum, Bounded)

main :: IO ()
main = do
  print Medium
  print (Small < Large, Medium == Medium)
  print [Small ..]
  print (maximum [Medium, Small, Large])
  print (succ Small, [minBound .. maxBound :: Size])
Medium
(True,True)
[Small,Medium,Large]
Large
(Medium,[Small,Medium,Large])

The derived Ord uses the order in which the constructors are written. Data types and writing your own classes and instances are covered in later lessons.

When a constraint is missing

If you use an operation without promising the class, GHC tells you which constraint to add:

haskell · try it yourself
same :: a -> a -> Bool
same x y = x == y

main :: IO ()
main = print (same 1 1)
<source>:2:14: error: [GHC-39999]
    * No instance for `Eq a' arising from a use of `=='
      Possible fix:
        add (Eq a) to the context of
          the type signature for:
            same :: forall a. a -> a -> Bool
    * In the expression: x == y
      In an equation for `same': same x y = x == y
  |
2 | same x y = x == y
  |              ^^

The fix is same :: Eq a => a -> a -> Bool.

Test yourself

What does the constraint in Ord a => a -> a -> a mean?

  1. a must be Int
  2. The function works for any type a that supports ordering
  3. The arguments must be sorted
  4. a must be a list

Which class provides show?

  1. Read
  2. Eq
  3. Show
  4. Enum

Why does [Small ..] work for data Size = Small | Medium | Large deriving (Enum)?

  1. All data types support ranges
  2. Range syntax needs an Enum instance, which deriving created
  3. Because of Show
  4. It doesn't work