Important Type Classes
Learn about the most important type classes.
We'll cover the following
Let’s continue by introducing a few more of the most important predefined Haskell type classes.
Comparing for equality with Eq
The type class Eq
contains all types that can be compared for equality using ==
. It is just as fundamental as Show
and implemented by all basic Haskell data types except functions. Its definition is
data Eq a where
(==), (/=) :: a -> a -> Bool
x /= y = not (x == y)
While the class Eq
contains two functions (the operators ==
and /=
), only the ==
operator needs to be implemented for defining an instance of the class. This is because the /=
operator contains a default implementation in the type class itself. Here it is defined as the negation of ==
. This makes it sufficient to only implement equality. We say that defining only ==
is a minimal complete definition for an Eq
instance.
Eq
instances can also be derived. The derived implementation of ==
on custom data types first compares the constructors and then recursively compares the values inside them.
For example, let’s derive Eq
for our Geometry
data type. We can derive it together with Show
at the same time.
Get hands-on with 1200+ tech skills courses.