Skip to content

Composing Monads

blancas edited this page Feb 6, 2013 · 6 revisions

Having seen some of the benefits of using these codified design patterns called monads, it is natural to ask whether it could be possible to combine their effect such that, for example, one might generate output on the side while keeping track of a stateful computation. It turns out that Morph provides a set of monads, similar to the ones described in the first section of this guide, but whose resulting value is itself a monad. These are called monad transformers and are the building blocks for working with nested monadic values. Thus composition of monads is done by using a monad type where we would otherwise use a regular data type.

To further illustrate the above, we present here sample code for the WriterT, which is similar to the Writer we have presented earlier, but whose computed value may be any other monad, including another monad transformer. WriterT's computed value will be an instance of the State monad. We start by loading the Morph core, monad and transf namespaces.

(use 'blancas.morph.core
     'blancas.morph.monads
     'blancas.morph.transf)

We will again with our now familiar expression evaluator. This time, however, we want both a logging facility and the ability to declare variables and clear the symbol table. Recall that in the first section we did one or the other but not both.