12 Interlude two: monads
In this chapter
- What is a monad, and why is it generalized abstract nonsense?
- Why are they useful to object-oriented programmers?
- What are Map and Bind?
- How are additive monads related to sequence operators?
In every programming language enthusiast’s life, there comes a time when they try to explain monads to anyone who will listen, and I’m no exception! Monads are a surprisingly simple and common design pattern that enables adding new capabilities on top of existing types. You’ve undoubtedly used monads many times quite happily without realizing you were doing so. Understanding that there was a deeper mathematical structure underlying seemingly unrelated types changed the way I approach program construction; in particular, monads are a useful way to structure programs as workflows of chained operations.
To understand why monads are so powerful, we’ll look at some examples of implementing a trivial operation on integers – divide by two – on integers that have been granted a special power, such as nullability, laziness, asynchrony, and so on. We’ll then come up with mechanisms for transforming any function taking any type into an equivalent monadic operation.