Tuesday, February 17, 2015

jQuery still not a Monad

I read jQuery is a Monad and thought yeah this is pretty cool I finally understand Monads.

jQuery is not a Monad, a Monad can take any type and it has a join operator that takes a doubly wrapped value and turn it into a singly wrapped one. This means that for it to be a Monad jQuery would have to work on any type, you have to be able to give it a String, Int or DOM and it operates on it consistently. jQuery's .map can only deal with the one type. It does have jquery.map but that would make the Array the Monad (or actually just a Functor) not jQuery.

Many of jQuery's method are specific to DOM manipulation, parsing and the like and not related to Monads in anyway - more like a combinator library like HXT.

The idea that it is a Monad still continues with, What jQuery can teach you about monads and Does jQuery expose a monadic interface?. One of the points that I think people ignore is that JavaScript has an implicit this and it affects how you apply function:
As is common with object-oriented language implementations, the this variable can be thought of as an implicitly-passed parameter, so we can then look through the API for a jQuery container looking for a method that takes one of these transformation callbacks and returns a new jQuery container.
This actually prevents you from easily (and definitely not clearly) writing Moands in JavaScript, Monads in the generic fashion that is required:
So, is jQuery or the Django ORM a monad? Strictly speaking, no. While the monad laws actually hold, they do so only in theory, but you can not actually use them in those languages as readily as you can in, say, Haskell. Methods get the object as the first (implicit, in JavaScript) argument, not the value(s) stored in the object. Methods are not first class objects independent from their classes. You can circumvent those restrictions by implementing some boiler code or, in Python, metaclasses that do some magic. What you get for doing that is a much easier time writing functions that work on all monadic classes, at the expense of making the whole concept more difficult to understand.
As Ed said: "jQuery is an amazing combinator library, but it isn't a functor, it isn't applicative, and it isn't a monad."
Post a Comment