I am trying to answer this question: "Given the algebraic data type
data Maybe a = Nothing | Just a
pick the correct instance declaration that shows that the type constructor
Maybe
is aMonad
." (taken from here:"DelftX: FP101x Introduction to Functional Programming".The way I am trying to anwer it is by compiling each potencial answer in turn, for example, this one:
instance Monad Maybe where return x = Just x Nothing >>= _ = Nothing (Just x ) >>= f = f x
I can not compile it because it is already defined in the prelude.
HwEx9.hs:16:10: error: Duplicate instance declarations: instance Monad Maybe -- Defined at HwEx9.hs:16:10 instance Monad Maybe -- Defined in `GHC.Base'
My question is: How can I compile it?
I would simply mimic the
Maybe
datatype, like:In the last versions of
ghc
, this will fail, since the last versions require that you implement applicative as well. We can do this like:Applicative
requires the type to be an instance ofFunctor
, so we can implement it like:It will then compile. The advantage of this approach is furthermore that we can easily compare the two
Maybe
monads, for example: