More Monads in Python
Simple implementations of the List and Maybe monads.
In the article on the Failure monad we looked at a simple definition of what a monad is:
A monad is a design pattern that allows us to add a context to data values, and also allows us to easily compose existing functions so that they execute in a context aware manner.
In this article we will look at two other common monads:
- List monads
- Maybe monads
List monads
A List monad allows us to process lists of values, without cluttering our code with looping constructs.
How a List monad is used
As with the Failure monad, our List monad should do three main things:
- Allow us to wrap a value (in this case, a list value) in a List monad.
- Allow us to apply an existing function to the entire list, using bind().
- Allow us to retrieve the List from a monad.
So a simple use might be like this:
k = List([1, 2, 3])
n = k.bind(neg)
print(n) # List([-1, -2, -3])
We will call our monad List
because that is the name that is commonly used for similar monads in other languages. Notice that…