Type classes
A class and its method
A type class is a set of method names with their types, and an instance is the implementation for one type. It is ad-hoc polymorphism: a function can behave differently for each type, where a parametrically polymorphic function such as length behaves the same for all of them.
class Greet a where
greet :: a -> String
instance Greet Bool where
greet True = "hello"
greet False = "bye"
instance Greet Int where
greet n = "number " ++ show n
The class declaration says that any type a with an instance has a function greet from a to String. The instances supply it, and the compiler picks one from the type of the value: greet True uses the Bool instance, greet (3 :: Int) the Int one.
Instances
An instance is a module-level declaration, not a value: it says how a type behaves for the whole program and cannot be switched at run time. GHC requires the instance to be in scope wherever the method is used, and refuses two instances for the same type and class, because the choice must be unambiguous.
module Main (main) where
class Greet a where
greet :: a -> String
instance Greet Bool where
greet True = "hello"
greet False = "bye"
instance Greet Int where
greet n = "number " ++ show n
main :: IO ()
main = do
putStrLn (greet True)
putStrLn (greet (3 :: Int))
ghc -Wall -O1 -o classes classes.hs
./classes
hello
number 3
The build is clean, which means both instances cover their types and the class has no default method that could be missing. A class may give a default implementation in the body of the class, and then an instance can omit that method; the Eq class of the Prelude defines /= in terms of == that way.
A constraint in a signature
A function that uses a method needs the class in its type, written before the arrow: Measured a => a -> Int is a function that works for every type with a Measured instance. That is the whole of the constraint syntax, and it is the same arrow that appears in the signatures of the Prelude.
module Main (main) where
class Measured a where
measure :: a -> Int
instance Measured [b] where
measure = length
instance Measured (Maybe b) where
measure Nothing = 0
measure (Just _) = 1
report :: Measured a => String -> a -> String
report label value = label ++ ": " ++ show (measure value)
main :: IO ()
main = do
putStrLn (report "list" ([1, 2, 3] :: [Int]))
putStrLn (report "maybe" (Just 'x'))
putStrLn (report "nothing" (Nothing :: Maybe Char))
ghc -Wall -O1 -o constraint constraint.hs
./constraint
list: 3
maybe: 1
nothing: 0
One function, three types of argument, no case analysis over the type in the body. The instance for lists uses length, the one for Maybe counts zero or one, and report is written once. Adding an instance for a new type extends the function without touching it: this is open extension, and it is what the derived instances of the next lesson build on.
The dictionary idea
Under the hood GHC compiles a class to a record of methods, a dictionary, and passes the right dictionary to every function with a constraint. A call to measure becomes a field access on that record. The details do not matter for writing programs, and the model explains three things that do:
- The dictionary is resolved at compile time, which is why the instance must be visible where the function is used.
- It is passed as an ordinary argument, which is why a constrained function is not slower in a surprising way and why it can be specialised away with -O1.
- Two instances for one type would mean two dictionaries and no way to choose, which is why GHC rejects them.
A class is not a Java interface: it does not bundle the data, only the operations, and a type can get an instance without being declared with the class in mind. That is why deriving can write an instance after the fact, and why the next lesson can add one by hand to a type from another module.
Exercises
- Add a Greet Char instance and print a greeting for a character.
- Write describeAll :: Greet a => [a] -> [String] with map greet.
- Add a second method to Measured with a default implementation and use it in report.
- Remove one instance from constraint.hs and read the error that names the missing instance.
- Define class Pair a where both :: a -> (a, a) and instance it for Int and Bool.
- Explain in two sentences why a class method needs a dictionary and a polymorphic function such as length does not.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a type class?
Answer
A set of method names with types, implemented per type by instances
A class declares operations, and each instance supplies them for one type.
-
What does
instance Greet Boolprovide?Answer
The implementation of greet for Bool
An instance implements the class methods for one concrete type.
-
What does the constraint
Measured a =>in a signature mean?Answer
The function works for any a that has a Measured instance
A constraint restricts the polymorphic type to those with the instance and passes the dictionary.
-
When does GHC choose which instance to use?
Answer
At compile time, from the types and the instances in scope
Instance selection is static, which is why the instance must be visible and must be unique.
-
What does this program print?
module Main (main) where class Greet a where greet :: a -> String instance Greet Bool where greet True = "hello" greet False = "bye" main :: IO () main = putStrLn (greet False)Answer
bye
False selects the Bool instance and its second equation.
-
Why does GHC reject two instances of the same class for the same type?
Answer
Two dictionaries would make the choice ambiguous
The instance is chosen from the type alone, so two candidates would have no resolution rule.
-
What does the dictionary model explain?
Answer
That a constraint is passed as a record of methods at compile time
GHC translates a class to a record of methods and passes the record to constrained functions.
-
What does
measure (Just (3 :: Int))return with the Measured instances of the lesson?Answer
1
The Maybe instance counts a Just as one element.
-
What does this program print?
module Main (main) where class Measured a where measure :: a -> Int instance Measured [b] where measure = length main :: IO () main = print (measure "abcd")Answer
4
A String is [Char], so the list instance applies and length counts four characters.
-
What can an instance do that a type declaration cannot?
Answer
Give an existing type a new class instance without changing the type
Instances are separate declarations, so a type can gain behaviour from another module.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev