6 Structuring programs with monad transformers
This chapter covers:
- Using monad transformers to extend a monad functionality
- Describing an application structure with monad stacks
- Defining your own monad transformers
- Overview of the most common monad transformers provided by the Haskell libraries
We’ve seen many monads already. You know that every monad specifies a way to combine two computations in sequence by implementing the >>=
operator. You also know that in a monadic setting we have a result of a computation with some additional effects: computations may fail (as in the Maybe
monad) or give an opportunity to communicate with the real world by doing input and otput (as in the IO
monad), you may mutate state or consult an environment in some other effectful computations. There are many other monads you may not be aware of but you already know what all of them share in common.
In this chapter we’ll discuss one simple question: how to express computations that need to use more than one monad at the same time? We’ll start with exploring the problem: let’s take a task that can be solved in one monad, find some flaws in that solution, and try to fix them. In Haskell it is often the case that there is a monad for that. But we have a monad already so the problem now is how to add another monad to a solution. Let’s see.