Monad transformer gotchas
There are two aspects of monad transformers that you will run into sooner or later. I will share them here so that you’ll be prepared.
Effect interaction
When stacking different two monad transformers, T1
and T2
, to combine two effects, you have a choice. Do you use T1 (T2 Identity)
or T2 (T1 Identity)
? Does it matter which one you choose?
In some cases, it doesn’t matter. For instance, in our earlier example of logging with levels, we combined the reader and writer effects, like so:
type App = ReaderT Config (Writer Log)
Recall that, because Writer w
is defined as WriterT w Identity
, this comes down to the following:
type App = ReaderT Config (WriterT Log Identity)
However, we could also have written the following:
type App = WriterT Log (ReaderT Config Identity)
As we have only interacted with this monad through the overloaded ask
and tell
operations, the only thing we need to change is the implementation of runApp
: