Is Maybe a Monad or MonadPlus?

In the All About Monads Haskell Wiki page, there is these definitions for the Maybe monad:

data Maybe a = Nothing | Just a

instance Monad Maybe where
  return = Just
  fail = Nothing
  Nothing >>= f = Nothing
  (Just x) >>= f = f x

instance MonadPlus Maybe where
  mzero = Nothing
  Nothing `mplus` x = x
  x `mplus` _= x

Which is the preferred, Maybe as an instance of a simple Monad, or as a MonadPlus?

Why could it not be both?

1 Like

Typeclasses are not exclusive! Maybe is an instance of a couple dozens of them.

2 Likes

MonadPlus is a completely different typeclass than Monad. The plus is because it gives a mplus operator to something that already has monad operators, not in the sense of C++.

So there is only one Monad instance in what you pasted.

Elaborating on what sclv said:

IIRC MonadPlus is the Monad version of the Alternative typeclass from Applicative. It’s a legacy feature; if we did it again, we’d just have Alternative.

For Alternative, look up Parser Combinators (Learn Haskell by Building Yourself a Scheme in 48 Hours is a great tutorial), which uses Alternative a lot.

2 Likes

In base we have

class (Alternative m, Monad m) => MonadPlus m where
   mzero :: m a
   mzero = empty -- from Alternative

   mplus :: m a -> m a -> m a
   mplus = (<|>) -- from Alternative

instance MonadPlus Maybe -- note empty instance, as we have a default implementation

In other words, don’t bother with MonadPlus, use Alternative at all times. It’s a very useful and ubiquitous typeclass, so nice to know it. MonadPlus is currently a backward-compatible alias for alternatives which are also monads.

1 Like