Open klequis opened 2 years ago
aka: class extension
Example
Eq
has two methods
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
Ord
extends/inherits Eq
Ord
gets the methods (==)
and (/=
) from Eq
Eq a
means the a
in Ord a
must be an instance of Eq
Eq
is a "superclass" of Ord
and Ord
is a "subclass" of Eq
class Eq a => Ord a where
compare :: a -> a -> Ordering
(<) :: a -> a -> Bool
(<=) :: a -> a -> Bool
(>) :: a -> a -> Bool
(>=) :: a -> a -> Bool
max :: a -> a -> a
min :: a -> a -> a
Musing
There are a couple of ways of looking at this. Yes, Ord gets methods from Eq and in a non-OO sense that could be called inheritance.
On the other hand class Eq a => Ord a where
also says that "any a
that is an Ord must already be an Eq. So a
in Ord
must be an Eq. It already has == and /= becuase it is already an Eq, not because it inherited those methods from Eq.
Type class inheritance is when a type class has a superclass. This is a way of expressing that a type class requires another type class to be available for a given type before you can write an instance:
Here, the type class
Fractional
inherits fromNum
. We could also say thatNum
is a superclass ofFractional
. The long and short of it is that if you want to write an instance ofFractional
for somea
, that typea
must already have an instance ofNum
before you may do so.Even though, in principle, this example could work, it will fail, because Nada doesn’t have a
Num
instance:Then, if you try to load it:
You need a
Num
instance first. Can’t write one that makes sense? Then you’re not allowed to have aFractional
instance, either.