[Haskell-cafe] Monad transformers

Roman Cheplyaka roma at ro-che.info
Sat Jul 3 15:02:50 EDT 2010

* Andrew Coppin <andrewcoppin at btinternet.com> [2010-07-03 15:07:17+0100]
> Roman Cheplyaka wrote:
> >* Andrew Coppin <andrewcoppin at btinternet.com> [2010-07-03 14:20:14+0100]
> >>In my experience, using more than one monad transformer at once makes
> >>code utterly incomprehensible.
> >
> >See X monad (xmonad) for an counterexample.
> >
> >-- | The X monad, 'ReaderT' and 'StateT' transformers over 'IO'
> >-- encapsulating the window manager configuration and state,
> >-- respectively.
> >--
> >-- Dynamic components may be retrieved with 'get', static components
> >-- with 'ask'. With newtype deriving we get readers and state monads
> >-- instantiated on 'XConf' and 'XState' automatically.
> >--
> >newtype X a = X (ReaderT XConf (StateT XState IO) a)
> In my experience, defining a type representing several stacked monad
> transformers is the easy part.

Of course it is. It wasn't my intention just to show you how easy it is
to define a newtype in Haskell :)

I just showed you a monad stack which is successfully used in xmonad --
and you really need to read the code a bit to get the taste of it.

> The hard part is figuring out how in
> the name of God to run the resulting computation

It is run just in the one place, so you don't need to think about it each
time you do some changes.

> or how to access functions burried at various levels of the stack.

See above:
-- Dynamic components may be retrieved with 'get', static components
-- with 'ask'.

So you use ask to get some configuration variable (reader monad is used
for configuration in xmonad) and get/put/modify to deal with dynamic
state of application. You use liftIO (abbreviated to 'io') to run IO

> From what I've seen, it usually ends up being faster and easier to
> just define a custom monad that does exactly what you want, and then
> use that.

In which way is it faster and easier? Can you show faster and easier
implementation of the X monad shown above?

Roman I. Cheplyaka :: http://ro-che.info/
"Don't let school get in the way of your education." - Mark Twain

More information about the Haskell-Cafe mailing list