shekhar
shekhar

Reputation: 49

Trouble understanding the source code of different instances of `MonadPlus` typeclass

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?

Upvotes: 1

Views: 83

Answers (1)

Aplet123
Aplet123

Reputation: 35560

The mzero = empty and mplus = (<|>) lines specify default implementations, which any implementor can override. empty and (<|>) come from the Alternative typeclass, which is defined for Maybes and lists as such:

instance Alternative Maybe where
    empty = Nothing
    Nothing <|> r = r
    l       <|> _ = l

instance Alternative [] where
    empty = []
    (<|>) = (++)

So, the Alternative definitions already match the default MonadPlus definitions, so they can simply write instance MonadPlus Maybe and use the defaults.

Essentially, the standard definition is still correct, it just expands out the defaults and takes Alternative out of the picture.

Upvotes: 3

Related Questions