Monad transformers
While two monads cannot be combined easily to form a third monad, there is a different mechanism, called monad transformers, that allows us to augment an existing monad with additional functionality.
The Reader transformer
As a first example of a (monad) transformer, we will visit the monad transformer, which adds the reading effect to an existing monad. This transformer is represented as follows:
Control.Monad.Trans.Reader
newtype ReaderT r m a = ReaderT { runReaderT :: r -> m a }
deriving Functor
As we can see, this looks a lot like the definition of Reader r a
from the previous chapter. The main difference is that it takes an additional type parameter, m
, for the monad that is being augmented. For example, we would use this as ReaderT Config (Writer Log)
to augment the Writer Log
monad with an implicit environment. That would give us our first App
representation. Similarly, we get the second App
representation by transforming IO
into...