Building Applications with Many Effects

Throughout this book you’ve learned several different ways to build up monadic computations that have their own particular properties, from Maybe computations that might not return a value and Either values that could succeed or have an error, to IO actions that might have any number of externally visible side effects like printing messages to the screen or updating an IORef . As you saw in the last chapter, many of the programs that we want to build involve several different types of effects that can be combined to build more sophisticated applications. Until now, when we’ve encountered a problem that required a novel combination of effects, we’ve built a new solution from scratch. Building up our computations from scratch each time we want something that uses a particular combination of effects might be instructive, but it also burdens us with the need to frequently rewrite the same code.

Monad transformers give us a better way forward, by allowing us to compose different types of monadic computation. In this chapter, you’ll learn how to break a more complex application down into smaller composable building blocks: individual monad transformers that you can combine in different ways, allowing you to re-use your code and combine your effects. First, we’ll revisit the problem of building a parser and look at how we can separate out the individual effects into their own independent re-usable modules. Next, you’ll learn about some of the challenges that you might encounter as you start combining monad transformers, including learning how to think carefully about the order that you compose transformers, and build some new modules to make it easier to combine functions that have different kinds of effects. Finally, we’ll look at the two popular monad transformer libraries, transformers and mtl , and you’ll how to use them together, and when you might prefer one or the other.