🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Typeclasses

A typeclass is a named set of operations that a type can support. A type that supports a typeclass can be used with that set of operations.

A constraint requires Eq support

The constraint Eq a => says the input type must support ==. The same function then works for numbers and for text.

same :: Eq a => a -> a -> Bool
same x y = x == y

main :: IO ()
main = print (same 4 4, same 4 5, same "go" "go")

show makes text and read parses text

show turns the number 42 into the text "42". read turns the text "42" back into a number, and the signature on answer fixes that number as an Int.

label :: String
label = show 42

answer :: Int
answer = read "42"

main :: IO ()
main = print (label, answer + 8)

compare reports LT, EQ, or GT

compare gives LT when the first value is smaller. It gives EQ for equal values and GT when the first value is bigger.

main :: IO ()
main = print (compare 2 3, compare 3 3, compare 5 3)

Example

same :: Eq a => a -> a -> Bool
same x y = x == y

half :: Fractional a => a -> a
half x = x / 2

main :: IO ()
main = print (same 9 9, compare 9 4, show 2024, half 7.0)

Key points

  • Eq: the Eq typeclass gives a type the == and /= operators.
  • Ord: the Ord typeclass gives a type the <, <=, >, and >= operators and the compare function.
  • Show: the Show typeclass gives a type the show function, which turns a value into text.
  • Read: the Read typeclass gives a type the read function, which turns text back into a value.
  • Num and Fractional: Num gives +, -, and *, and Fractional gives /.
  • Constraint: a constraint like Eq a => in a signature requires the type a to support Eq.

In this example, same uses the Eq constraint and reports that 9 equals 9. compare comes from Ord and reports GT because 9 is bigger than 4. show comes from Show and turns 2024 into text. half uses the Fractional constraint, and half of 7.0 is 3.5.

Note

a typeclass is a set of operations, not a type itself.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

Which typeclass gives a type the == operator?