I'm going through the source code of the MonadPlus typeclass and its instances like Maybe, [] etc. I don't find the methods of these instances - mzero or mplus defined. Here's the source code of Maybe instance of MonadPlus:
class (Alternative m, Monad m) => MonadPlus m where
mzero :: m a
mzero = empty
mplus :: m a -> m a -> m a
mplus = (<|>)
instance MonadPlus Maybe
While in Chapter 15 of Real World Haskell it says that the following are the standard definitions of mzero and mplus for Maybe and [].
class Monad m => MonadPlus m where
mzero :: m a
mplus :: m a -> m a -> m a
instance MonadPlus [] where
mzero = []
mplus = (++)
instance MonadPlus Maybe where
mzero = Nothing
Nothing `mplus` ys = ys
xs `mplus` _ = xs
So essentially my question is why there's the difference?
The
mzero = emptyandmplus = (<|>)lines specify default implementations, which any implementor can override.emptyand(<|>)come from theAlternativetypeclass, which is defined for Maybes and lists as such:So, the
Alternativedefinitions already match the defaultMonadPlusdefinitions, so they can simply writeinstance MonadPlus Maybeand use the defaults.Essentially, the standard definition is still correct, it just expands out the defaults and takes
Alternativeout of the picture.