Search code examples
haskellshowoption-typeeitherderiving

Why does Either derives Show but Maybe does not?


Documentation of both Either and Maybe indicate that they have instances of Show.

Either is defined as deriving Show, simply :

data  Either a b  =  Left a | Right b
  deriving (Eq, Ord, Read, Show, Typeable)

Yet, Maybe does not :

data  Maybe a  =  Nothing | Just a
  deriving (Eq, Ord)

Since they are part of base and are so similar why doesn't Maybe directly derive Show?

Another question might also be, where does it get its Show instance?


Solution

  • The instance for Maybe is defined explicitly in GHC.Show, along with instances for a whole bunch of other common types like tuples. You can find out where an instance was defined using the :i command in ghci:

    Prelude> :i Maybe
    data Maybe a = Nothing | Just a     -- Defined in ‘Data.Maybe’
    instance Eq a => Eq (Maybe a) -- Defined in ‘Data.Maybe’
    instance Monad Maybe -- Defined in ‘Data.Maybe’
    instance Functor Maybe -- Defined in ‘Data.Maybe’
    instance Ord a => Ord (Maybe a) -- Defined in ‘Data.Maybe’
    instance Read a => Read (Maybe a) -- Defined in ‘GHC.Read’
    instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’
    

    I don't know why they defined the instance explicitly or put it in GHC.Show instead of Data.Maybe—as far as I can tell, it could be moved to Data.Maybe and/or derived. My guess is that they did not want Data.Maybe to depend on anything except GHC.Base (as it does now), presumably because it's used in some of the other core modules.