Haskell Custom Type Classes
deriving writes standard instances for you, but often you want to decide yourself how a type is shown or compared, or define a brand-new class of your own. This lesson covers both: writing instances by hand and declaring classes.
Writing an instance by hand
An instance declaration says "this type belongs to this class" and defines the class's methods for it:
data Card = Card Rank Suit
data Suit = Hearts | Spades deriving (Eq, Ord)
data Rank = Num Int | Jack | Queen | King | Ace deriving (Eq, Ord)
instance Show Suit where
show Hearts = "H"
show Spades = "S"
instance Show Rank where
show (Num n) = show n
show Jack = "J"
show Queen = "Q"
show King = "K"
show Ace = "A"
instance Show Card where
show (Card r s) = show r ++ show s
main :: IO ()
main = do
print (Card Queen Hearts)
print [Card (Num 7) Spades, Card Ace Hearts]
print (Num 10 < Jack, Ace > King)QH
[7S,AH]
(True,True)
Custom Show instances are fine for display, but by convention show should produce something that looks like Haskell code when possible. For user-facing output, many programmers prefer a separate function such as render :: Card -> String.
Instances with a meaning: Eq that ignores case
Sometimes the derived behaviour is wrong for your domain. Here two usernames are equal regardless of upper and lower case:
import Data.Char (toLower)
newtype Username = Username String
instance Eq Username where
Username a == Username b = map toLower a == map toLower b
instance Show Username where
show (Username u) = '@' : u
main :: IO ()
main = do
print (Username "Ada" == Username "ada")
print (Username "Ada" /= Username "Bob")
print (Username "Ada" `elem` [Username "BOB", Username "ADA"])True
True
True
We only defined ==; /= came for free, because the Eq class has a default implementation of /= in terms of ==. Each class documents its minimal complete definition: for Eq it is == or /=; for Ord it is compare or <=; for Show it is show or showsPrec.
Declaring your own class
A class declaration lists method names and their types, using a type variable for "the instance type":
class Describable a where
describe :: a -> String
name :: a -> String
name _ = "thing" -- default implementation
-- uses the other methods: works for every instance
headline :: a -> String
headline x = name x ++ ": " ++ describe x
data Planet = Planet String Double -- name, radius in km
data Dog = Dog String Int -- name, age
instance Describable Planet where
describe (Planet _ r) = "a planet with radius " ++ show r ++ " km"
name (Planet n _) = n
instance Describable Dog where
describe (Dog _ age) = "a dog aged " ++ show age
instance Describable Bool where
describe True = "yes"
describe False = "no"
main :: IO ()
main = do
putStrLn (headline (Planet "Mars" 3389.5))
putStrLn (headline (Dog "Rex" 4))
putStrLn (headline True)Mars: a planet with radius 3389.5 km
thing: a dog aged 4
thing: yes
Any type, including built-in ones like Bool, can become an instance of your class. That is a key difference from interfaces in many object-oriented languages: you can add a class to a type after both have been written.
Polymorphic functions over your class
Functions can now require the class with a constraint:
class Shape a where
area :: a -> Double
perimeter :: a -> Double
data Circle = Circle Double
data Rect = Rect Double Double
instance Shape Circle where
area (Circle r) = pi * r * r
perimeter (Circle r) = 2 * pi * r
instance Shape Rect where
area (Rect w h) = w * h
perimeter (Rect w h) = 2 * (w + h)
compactness :: Shape a => a -> Double
compactness s = 4 * pi * area s / perimeter s ^ 2
report :: Shape a => String -> a -> String
report label s = label ++ ": area " ++ show (round (area s) :: Int) ++ ", compactness " ++ show (roundTo 3 (compactness s))
where
roundTo n x = fromIntegral (round (x * 10 ^ n) :: Int) / 10 ^ n
main :: IO ()
main = do
putStrLn (report "circle" (Circle 10))
putStrLn (report "square" (Rect 10 10))
putStrLn (report "strip" (Rect 100 1))circle: area 314, compactness 1.0
square: area 100, compactness 0.785
strip: area 100, compactness 3.1e-2
A circle is the most compact shape (exactly 1), and a long strip is very far from it. Note how show prints small doubles in scientific notation (3.1e-2 is 0.031).
Note: A list must hold values of one type, so
[Circle 1, Rect 2 3]is a type error even though both areShapes. The usual fix is a single sum type (data AnyShape = C Circle | R Rect) or a record of functions. Type classes are for choosing behaviour by type, not for heterogeneous collections.
Instances for parameterised types
An instance can depend on an instance for the type parameter. Here a Box a is showable whenever a is:
data Box a = Box a | Empty
instance Show a => Show (Box a) where
show (Box x) = "[" ++ show x ++ "]"
show Empty = "[ ]"
main :: IO ()
main = do
print (Box 42)
print (Box "gift")
print [Box True, Empty]
print (Box (Box 'x'))[42]
["gift"]
[[True],[ ]]
[['x']]
The Show a => in the instance head says: "to show a Box a, I need to be able to show an a".
Test yourself
If you define only == in an Eq instance, where does /= come from?
- It is unavailable
- From a default method in the
Eqclass - GHC derives it from
Show - You must always define both
Can you make the built-in type Bool an instance of a class you just declared?
- No, built-in types are closed
- Yes, any type can get an instance of any class
- Only with
deriving - Only if the class is in the Prelude
What does instance Show a => Show (Box a) mean?
- Every type is showable
Box acan be shown wheneveracan be shownamust beBoxShowis derived