Chapter 11. Monads

 

In the previous chapter, we introduced a simple algebraic structure, the monoid. This was our first instance of a completely abstract, purely algebraic interface, and it led us to think about interfaces in a new way. A useful interface may be defined only by a collection of operations related by laws.

In this chapter, we’ll continue this mode of thinking and apply it to the problem of factoring out code duplication across some of the libraries we wrote in parts 1 and 2. We’ll discover two new abstract interfaces, Functor and Monad, and get more general experience with spotting these sorts of abstract structures in our code.[1]

1 The names functor and monad come from the branch of mathematics called category theory, but it isn’t necessary to have any category theory background to follow the content in this chapter. You may be interested in following some of the references in the chapter notes for more information.

11.1. Functors: generalizing the map function

In parts 1 and 2, we implemented several different combinator libraries. In each case, we proceeded by writing a small set of primitives and then a number of combinators defined purely in terms of those primitives. We noted some similarities between derived combinators across the libraries we wrote. For instance, we implemented a map function for each data type, to lift a function taking one argument “into the context of” some data type. For Gen, Parser, and Option, the type signatures were as follows:

11.2. Monads: generalizing the flatMap and unit functions

11.3. Monadic combinators

11.4. Monad laws

11.5. Just what is a monad?

11.6. Summary

sitemap