Chapter 6. Using Typeclasses
Typeclasses are among the most powerful features in Haskell. They allow us to define generic interfaces that provide a common feature set over a wide variety of types. Typeclasses are at the heart of some basic language features such as equality testing and numeric operators. Before we talk about what exactly typeclasses are, though, we’d like to explain the need for them.
The Need for Typeclasses
Let’s imagine that for some
unfathomable reason, the designers of the Haskell language neglected
to implement the equality test ==
.
Once you get over your shock at hearing this, you resolve to implement
your own equality tests. Your application consists of a simple Color
type, and so your first equality test is
for this type. Your first attempt might look like this:
-- file: ch06/naiveeq.hs data Color = Red | Green | Blue colorEq :: Color -> Color -> Bool colorEq Red Red = True colorEq Green Green = True colorEq Blue Blue = True colorEq _ _ = False
You can test this with ghci:
ghci>
:load naiveeq.hs
[1 of 1] Compiling Main ( naiveeq.hs, interpreted ) Ok, modules loaded: Main.ghci>
colorEq Red Red
Trueghci>
colorEq Red Green
False
Now, let’s say that you want to add an
equality test for String
s. Since a
Haskell String
is a list of
characters, we can write a simple function to perform that test. For
simplicity, we cheat a bit and use the ==
operator here to
illustrate:
-- file: ch06/naiveeq.hs stringEq :: [Char] -> [Char] -> Bool -- Match if both are empty stringEq ...
Get Real World Haskell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.