klequis / zz-haskell-notebook

Notes from learning Haskell
1 stars 0 forks source link

Type class inheritance #45

Open klequis opened 2 years ago

klequis commented 2 years ago

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:

class Num a => Fractional a where
    (/) :: a -> a -> a
    recip :: a -> a
    fromRational :: Rational -> a

Here, the type class Fractional inherits from Num. We could also say that Num is a superclass of Fractional. The long and short of it is that if you want to write an instance of Fractional for some a, that type a must already have an instance of Num before you may do so.

Even though, in principle, this example could work, it will fail, because Nada doesn’t have a Num instance:

newtype Nada =
    Nada Double deriving (Eq, Show)
instance Fractional Nada where
    (Nada x) / (Nada y) = Nada (x / y)
    recip (Nada n) = Nada (recip n)
    fromRational r = Nada (fromRational r)

Then, if you try to load it:

- No instance for (Num Nada)
    arising from the superclasses of an
        instance declaration
- In the instance declaration for
    ‘Fractional Nada’

You need a Num instance first. Can’t write one that makes sense? Then you’re not allowed to have a Fractional instance, either.

klequis commented 2 years ago

Type class inheritance

aka: class extension

Example

Eq has two methods

class Eq a where
  (==) :: a -> a -> Bool
  (/=) :: a -> a -> Bool
klequis commented 2 years ago

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.