The following code from "Haskell Programming: From first principles" fails to compile:
module Learn where
import Data.Semigroup
import Data.Monoid
-- Exercise: Optional Monoid
data Optional a = Nada
| Only a
deriving (Eq, Show)
instance Monoid a => Monoid (Optional a) where
mempty = Nada
mappend Nada Nada = Nada
mappend (Only a) Nada = Only $ mappend a mempty
mappend Nada (Only a) = Only $ mappend mempty a
mappend (Only a) (Only b) = Only $ mappend a b
It gives the following error:
intermission.hs:11:10: error:
• Could not deduce (Semigroup (Optional a))
arising from the superclasses of an instance declaration
from the context: Monoid a
bound by the instance declaration at intermission.hs:11:10-40
• In the instance declaration for ‘Monoid (Optional a)’
|
11 | instance Monoid a => Monoid (Optional a) where
|
In order to stop ghc from complaining, I had to create a semigroup instance of Optional a and define "<>". This doesn't quite make sense to me and was wondering if there was something I was overlooking.