chapter eleven

11 Monads and functors

 

This chapter covers:

  • Defining the functor by generalizing the map operation
  • Deriving general purpose methods by applying the functor
  • Revisiting and formalizing the functor law
  • Defining various combinators that constitute the monad
  • Introducing and proving the laws that govern the monad
  • Discovering the true meaning of the monad

Many developers break out in a cold sweat on hearing the term monad. We have visions of people sitting in their lofty ivory towers, completely disconnected from the reality that we live in. We hear them mumbling away about academic concepts that have little or no bearing on the real world.

Even though individuals have used the term monad in such ways in the past, we hope to show that this can be no further from the truth. The monad concept is highly practical in its application, and can truly transform the way we write code. Granted, this term (along with its relative the functor, which we will also come to know in this chapter) does find its origins in the academic roots of category theory. Despite this, we will learn that it’s highly practical and nothing to fear.

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

11.1  Functors: generalizing the map function

11.1.1  The importance of laws and their relation to 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

11.6  Summary