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

Chris Wong chrisyco+haskell-cafe at gmail.com
Mon Dec 10 23:07:35 CET 2012


Hi Petr,

On Sun, Dec 9, 2012 at 7:59 AM, Petr P <petr.mvd at gmail.com> wrote:
>
> 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.

How I see it, the MTL classes are there to lift operations
automatically through layers of transformers. They're just a hack to
avoid having to call `lift` all the time, and aren't really designed
to be used on monads other than the original WriterT.

With this interpretation, the constraint makes sense -- it is simply
reflecting the constraints already on the concrete monad.

Chris

> 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
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>



More information about the Haskell-Cafe mailing list