The wonders of monads are finally revealed without resorting to Category Theory
are one of the key enablers of Ajax. Monads are amazing. They are simple
things, almost trivially implemented, with enormous power to manage complexity.
But understanding them is surprisingly difficult, and most people, once they
have that ah-ha moment, seem to lose the ability to explain them to others.
Well I’m not going to try. I do, however, wish to convey my realizations about monads.
First let me just offer this piece of Underscore code:
Basically take the input and perform a series of computations on them with each step returning the result of the computation ready for the next. But that code looks… well… yucky. Lets try again:
Holy Pyramid of Doom Batman! Lets not do that again. Thank goodness
Underscore offers such better expressive syntax. Using the
wraps a variable in a special Underscore object. When you call a methods on
that object the return value of the method is the same wrapped object.
Much better. It’s readable, concise, and guess what… That’s a monad! Yes it is a way to represent data with a wrapper around that data that exposes a way to do computations on the data. This opens up the opportunity to expressively compose those computations in a human readable way. There are many other advantages as well which are out of scope for this post. Oh, and in case you hadn’t made the connection, jQuery is also a monad!
My monad discovery
I came to understand monads only after I accidentally created one. I was working on a piece of browser code. A plug-in for text fields. I needed to create and modify DOM elements. I wanted to do this without jQuery, and support IE8 (don’t ask). I realized that there was a lot of complexity supporting IE8 with Vanilla JS so I wanted to write a simple abstraction around it.