[Haskell-cafe] generalizing the writer monad

Strake strake888 at gmail.com
Thu Oct 18 05:10:43 CEST 2012

 On 17/10/2012, Petr P <petr.mvd at gmail.com> wrote:
>     Hi,
> (this is a literate Haskell post.)
> lately I was playing with the Writer monad and it seems to me that it
> is too tightly coupled with monoids. Currently, MonadWriter makes the
> following assumptions:
> (1) The written value can be read again later.
> (2) For that to be possible it has to be monoid so that multiple (or
> zero) values can be combined.
> I fell say that this is a bit restricting. Sometimes, the written
> value can be lost - either used to compute something else or for
> example sent out using some IO action to a file, network etc. For
> example, I'd like to create an IO-based writer monad whose `tell` logs
> its argument somewhere - prints it, stores to a file etc.

No need:

newtype SequenceM m a = SequenceM (m a);

instance (Monad m, Monoid a) => Monoid (SequenceM m a) where {
  mempty = SequenceM (return mempty);
  SequenceM mx `mappend` SequenceM my = SequenceM (liftM2 mappend mx my);

whatever :: (MonadWriter (SequenceM IO ()) m) => m ();
whatever = tell (SequenceM (someIO :: IO ()));


More information about the Haskell-Cafe mailing list