1
votes

I am trying to implement WriterT with custom data type. I have implemented the monoid as the required by runWriterT. But I am unable to compile the code. I get an error

Could not deduce (Semigroup (Env a)) arising from the superclasses of an instance declaration from the context: Num a

import Control.Monad
import Control.Monad.Trans.Reader
import Control.Monad.IO.Class
import Control.Monad.Trans.Writer
import Control.Monad.Trans
import Data.Monoid

newtype Env a = Env { getEnv :: a  }  deriving (Eq, Ord, Read, Show)


instance Num a => Monoid (Env a) where
  mempty = Env 0
  Env x  `mappend` Env y = Env (x + y)


writeSomething :: (Num a) => WriterT (Env a) IO ()
writeSomething = do
  tell $ Env 1
  tell $ Env 3
1
Env just looks like Data.Monoid.Sum.amalloy
Yes it is. But I wanted to write a custom monoid.DBS

1 Answers

5
votes

In recent GHCs, Semigroup is a superclass of Monoid, so to create an instance of Monoid correctly, you must also create an instance of Semigroup. Luckily it's generally quite short:

instance Num a => Semigroup (Env a) where (<>) = mappend