Introducing Monads

Over the last two chapters, you learned about the the Functor and Monad type classes by writing code that interacted with the real world using IO . Although IO is a great introduction to these type classes, there are many other ways that Functor and Monad are useful that have nothing to do with side effects or  IO .

Monad in particular has a bit of a reputation in Haskell as being both extremely important as well as difficult to learn. Throughout this chapter, you’ll work your way up to creating your own Monad type class and writing your own Monad instances incrementally. In the process, you’ll learn the hows and whys that will remove some of the mystery from the type class.

Before we can dive into the details of monads though, we’ll need to spend some time with two other other important type classes, Functor and Applicative . These three type classes form a hierarchy. All Monad instances must also have an Applicative instance, and all Applicative instances must in turn also have a Functor instance. We’ll start by working our way through these three type classes from bottom to top, starting with Functor . You’ll have the chance to create your own definitions for these type classes, and reimplement the instances for several common types to get a handle on how they work. Finally, at the end of the chapter we’ll look at the rules that govern how these instances should be implemented so that they are well behaved and work as you would expect.