Most monad tutorials are long, confusing, and ineffective. I cannot promise this one will be more clear, more interesting, or even more effective, but I can at least promise to make it brisk. You have nothing to lose by reading it.
Take a look at this object,
Foo. It’s a monad, but what that means isn’t relevant right now. Let’s just focus on how Foo specifically works:
1 2 3 4 5 6 7
Foo holds a single
value that never changes. It provides a method for
getting it, and a curious method named
bind. Bind gets a function, passes it the
value, and then returns the result in a new Foo.
Because bind returns a new Foo, it’s chainable:
1 2 3
This chaining is kinda neat – it lets me write the operations I want to perform on x in order, rather than with nested function calls, like below:
But the real value to an object like Foo is that if I put logic inside
bind, I can abstract away an action that I want to perform between each step of an operation.
Consider another monad, named
1 2 3 4 5 6 7 8
If I have an operation that makes multiple changes to a value, and I want to log how that value mutates at each turn,
Bar lets me swap code like this…
1 2 3 4 5 6
…for code like this:
1 2 3 4
You now understand monads. I did promise this would be quick. Monads can be boiled down – roughly – to the following rules:
- A monad contains a value
- A monad has a method named
bindthat takes a function
- Bind has some logic around calling that function and processing the result
- Bind then returns the result in a new monad, so that calls to bind can be chained
That’s it. If you understand how the above code works, you understand monads. Sorry if you were hoping for something more magical and mind-bending.
We can do anything we like in
bind. Anything that we want to do between the steps of an operation – be that deciding how we pass the value into the next step, or doing something with the result that comes back out – we can put inside
bind and abstract away. Null checking is a great example:
1 2 3 4 5 6 7 8 9 10
Maybe, bind only calls the supplied function if it can hand it a valid, non-null value. Otherwise it quietly returns a clone of itself. This lets us turn verbose, repetitive code like this…
1 2 3 4
…into a much more elegant alternative:
1 2 3 4 5 6 7
Hopefully these two examples are enough to show you why monads and their bind methods are so powerful. No doubt you can imagine uses of your own.
There are scores of other monads, all with quite diverse uses and functionality. But they all follow those same four rules we saw in
Bar. Provided you stick to them, you are using the monad pattern, and now ostensibly have sufficient functional programming credence to immediately declare yourself a greybeard FP maven, lording it over the programming masses.