11 Monads and functors

 

This chapter covers

  • Defining functors by generalizing the map operation
  • Deriving general-purpose methods by applying functors
  • Revisiting and formalizing the functor law
  • Defining combinators that constitute monads
  • Proving the laws that govern monads

Many of us break out in cold sweat on hearing the word monad. We have visions of people in lofty ivory towers, wholly disconnected from reality, looking down on the rest of humanity with disdain. We hear them mumbling academic concepts that have little or no bearing on the real world.

Even though many have used this word in such ways, we hope to show you that it could not be further from the truth. The monad concept is pragmatic and can transform the way we write code. Granted, this term and its relative, functor (which we will also come to know in this chapter), have their origins in category theory’s academic roots. Despite that, we will learn of its practical nature and that there is nothing to fear.

This chapter serves to demystify the ominous monad. By the end of it, you should have a working understanding of what a monad is and how to apply it in a pragmatic way to your daily programming challenges. This could well be one of the most important lessons you learn from this book.

11.1 Functors

11.1.1 Defining the functor by generalizing the map function

11.1.2 The importance of laws and their relation to the functor

11.2 Monads: Generalizing the flatMap and unit functions

11.2.1 Introducing the Monad interface

11.3 Monadic combinators

11.4 Monad laws

11.4.1 The associative law

11.4.2 Proving the associative law for a specific monad

11.4.3 The left and right identity laws

11.5 Just what is a monad?

11.5.1 The identity monad

11.5.2 The State monad and partial type application