Haskell Typeclasses

Priyanka Mondal
2 min readApr 18, 2020

--

Haskell typeclasses can be difficult to understand for those who are new to Haskell. I hope this article will make it easier for you to understand.

Typeclasses are basically a set of functions that can be thought of as behaviors. When a programmer defines a new type, they need to define new behaviors for that type. Sometimes different types can have same kinds of behaviors. So, instead of defining these behaviors separately for each type, they can make their types as instances of a typeclass. Let us go through the following examples of types and typeclasses to understand things in a better way.

data Gray = White | Blackclass Eqc a where
isEqual :: a -> a -> Bool

The name of the typeclass is Eqc, and a is the instance type. A typeclass can have many functions, here only one function is shown for simplicity. An instance of this typeclass needs to implement the function isEqual. Now let us show an instance of this typeclass.

instance Eqc Gray where
isEqual White White = True
isEqual White Black = False
isEqual Black White = False
isEqual Black Black = True

We can test our code on ghci as well.

ghci> isEqual White White
True

Now let us see how we can use the same Eqc typeclass with a different type instance.

data MyBool = Zero | Oneinstance Eqc MyBool where
isEqual Zero Zero = True
isEqual Zero One = False
isEqual One Zero = False
isEqual One One = True

We can again verify our implementation on ghci

ghci> isEqual One Zero
False

So, if we did not have the isEqual function of Eqc typeclass then we had to define two separate equality determining functions for both Gray and MyBool types. But with Eqc typeclass we got rid of that redundancy.

Now let us check the type of isEqual

ghci>  :t isEqual
isEqual :: Eqc a => a -> a -> Bool

This means that — isEqual takes two parameters of type a ( where a is an instance of Eqc ) and returns a type Bool.

Now let us see some typeclass with multiple functions.


data RGB = Red | Green | Blue
class Eqrgb a where
isRed :: a -> Bool
isGreen :: a -> Bool
isBlue :: a -> Bool
isYellow :: a -> a -> Bool
instance Eqrgb RGB where
isRed Red = True
isRed _ = False
isGreen Green = True
isGreen _ = False
isBlue Blue = True
isBlue _ = False
isYellow Green Blue = True
isYellow Blue Green = True
isYellow _ _ = False

just to verify things on ghci

ghci> isYellow Red Green
False
ghci> isYellow Green Blue
True
ghci> isRed Red
True

Hope you enjoyed reading !

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response