Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 57 ยท Types and values

Type Classes: Eq, Ord, Show, Read, Num

Understand Haskell type classes and constraints like Eq a =>, learn Eq, Ord, Show, Read and Num, use deriving, and see how numeric defaulting works.

Some operations make sense for many types but not all of them. You can compare two numbers with ==, but you cannot compare two functions. Haskell captures this with type classes: a type class is a named group of operations that a type can support. This lesson introduces the five classes you will see everywhere, how constraints appear in signatures, how deriving writes instances for you, and how numeric defaulting works.

All Haskell blocks here are read-only. The JavaScript stand-ins model a class as an object of functions, which is the same idea Haskell compiles to, but without any compile-time checking.

Constraints in signatures

Look at the type of ==:

HASKELL
(==) :: Eq a => a -> a -> Bool

Read it as: "for any type a that is in the class Eq, == takes two as and returns a Bool". The part before => is the constraint. It restricts the type variable, and that restriction is what lets the function use equality on a at all.

HASKELL
isSame :: Eq a => a -> a -> Bool
isSame x y = x == y

largest :: Ord a => a -> a -> a
largest x y = if x >= y then x else y

Without the Ord a constraint, the second function would not compile: GHC cannot know that an arbitrary a supports >=. Several constraints go in parentheses: (Show a, Ord a) => ....

The standard classes

Five classes to know first

Eq Types you can test for equality.
Ord Types with an ordering.
Show Types you can turn into text.
Read Types you can parse from text.

Num covers numeric types, and comes next.

1 / 2

Eq

Eq provides == and /=. Almost every ordinary type has it, but functions do not.

HASKELL
ghci> 3 == 3
True
ghci> "abc" /= "abd"
True
ghci> [1, 2] == [1, 2]
True

Ord

Ord builds on Eq and adds <, <=, >, >=, max, min and compare. compare returns a value of the type Ordering, which is one of LT, EQ or GT:

HASKELL
ghci> compare 2 5
LT
ghci> max "apple" "banana"
"banana"
ghci> compare (3, 'a') (3, 'b')
LT

Strings and tuples compare element by element, like a dictionary.

Show and Read

show turns a value into a String; read goes the other way. Show and Read are the basis of simple printing and parsing:

HASKELL
ghci> show 42
"42"
ghci> show "hi"
"\"hi\""
ghci> show [1, 2, 3]
"[1,2,3]"
ghci> read "42" :: Int
42
ghci> read "[1,2,3]" :: [Int]
[1,2,3]

Note that show "hi" includes the quotes, because it produces Haskell syntax. read needs to know which type you want, which is why :: Int is there; GHC cannot guess. read "oops" :: Int crashes with Prelude.read: no parse. Later lessons, such as Maybe and Either, show safer ways to parse.

print x is simply putStrLn (show x).

Num

Num is the class of numeric types: Int, Integer, Double and others are all instances. It provides +, -, *, negate, abs, signum and fromInteger. It deliberately does not include division, because whole numbers and fractions divide differently:

HASKELL
(/)  :: Fractional a => a -> a -> a      -- for Double, Rational, ...
div  :: Integral a   => a -> a -> a      -- for Int, Integer, ...

This is why 7 / 2 works and gives 3.5, while 7 div 2 gives 3. If you write length xs / 2, GHC reports a missing instance, since length returns Int, which is not Fractional. Convert first: fromIntegral (length xs) / 2.

Letting the compiler write instances

To compare or print your own type, it needs instances. For standard classes you can ask GHC to write them with deriving:

HASKELL
data Color = Red | Green | Blue
  deriving (Eq, Ord, Show, Read, Enum, Bounded)

ghci> Red == Red
True
ghci> Red < Blue
True
ghci> show Green
"Green"
ghci> read "Blue" :: Color
Blue
ghci> [minBound .. maxBound] :: [Color]
[Red,Green,Blue]

For Ord, constructors are ordered by their position in the declaration, so Red < Green < Blue. The syntax data Color = ... is explained in algebraic data types. Writing instances by hand comes in custom type classes.

Numeric defaulting

A literal like 3 has the type Num a => a. If nothing else decides the type, GHC defaults it so the program can run: it tries Integer first, then Double. That is why this works in GHCi:

HASKELL
ghci> 2 ^ 70
1180591620717411303424
ghci> 7 / 2
3.5

The first is an Integer (an Int would overflow); the second falls to Double because / needs Fractional. Defaulting applies only when the constraints are the standard numeric ones. If you mix in a class it does not know about, you get an ambiguous type error. The classic example is:

HASKELL
main = print (read "5")      -- error: ambiguous type variable

GHC cannot decide what type to read, so it asks you to say. Fix it with print (read "5" :: Int).

Common mistakes

  • Missing constraint. Writing largest :: a -> a -> a and using >= inside is rejected; add Ord a =>.
  • Comparing functions. (+ 1) == (+ 1) fails, because functions have no Eq instance.
  • / on integers. Convert with fromIntegral, or use div.
  • read without a type. Annotate the result or let the context decide it.

Stand-in: a class as a dictionary

When GHC compiles a constrained function, it passes the class operations along as a hidden argument, often called a dictionary. This JavaScript stand-in makes that visible. It is a model of the mechanism, not a type checker.

JS Classes as dictionaries

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A second model imitates deriving for a three-constructor type, with ordering by position and [minBound .. maxBound]:

JS What deriving gives you

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the Eq a => in isSame :: Eq a => a -> a -> Bool mean?

    Text before => is a constraint; here a must be an instance of Eq.
  2. 2. What is the value of show "hi"?

    show produces Haskell syntax, so a string is shown with its surrounding quotes.
  3. 3. What does compare 2 5 return?

    compare returns an Ordering: LT, EQ or GT. Two is less than five.
  4. 4. Why does length xs / 2 fail to compile?

    Use fromIntegral (length xs) / 2 to convert the Int first.
  5. 5. What does deriving (Eq, Ord) on a data type give you?

    GHC writes the instances for you. For Ord, an earlier constructor is smaller than a later one.

Summary

  • A type class groups operations; a constraint such as Ord a => says which classes a type variable must belong to.
  • Eq is equality, Ord ordering (compare gives LT, EQ or GT), Show turns values into text and Read parses text.
  • Num covers numbers; / needs Fractional, div needs Integral.
  • deriving writes standard instances for your own types.
  • Number literals default to Integer, then Double; ambiguous types such as read "5" need an annotation.

Next: Tuples and Lists.