[Haskell-cafe] mtl: Why there is "Monoid w" constraint in the definition of class MonadWriter?

Edward Z. Yang ezyang at MIT.EDU
Sat Dec 8 20:19:01 CET 2012


The monoid instance is necessary to ensure adherence to the monad laws.

Cheers,
Edward

Excerpts from Petr P's message of Sat Dec 08 10:59:25 -0800 2012:
> The class is defined as
> 
> > class (Monoid w, Monad m) => MonadWriter w m | m -> w where
> >   ...
> 
> What is the reason for the Monoid constrait? It seems superfluous to me. I
> recompiled the whole package without it, with no problems.
> 
> 
> Of course, the Monoid constraint is necessary for most _instances_, like in
> 
> > instance (Monoid w, Monad m) => MonadWriter w (Lazy.WriterT w m) where
> > ...
> 
> but this is a different thing - it depends on how the particular instance
> is implemented.
> 
> I encountered the problem when I needed to define an instance where the
> monoidal structure is fixed (Last) and I didn't want to expose it to the
> user. I wanted to spare the user of of having to write Last/getLast
> everywhere. (I have an instance of MonadWriter independent of WriterT, its
> 'tell' saves values to a MVar. Functions 'listen' and 'pass' create a new
> temporary MVar. I can post the detail, if anybody is interested.)
> 
> Would anything break by removing the constraint? I think the type class
> would get a bit more general this way.
> 
>   Thanks for help,
>   Petr Pudlak



More information about the Haskell-Cafe mailing list