I read somewhere that jQuery is a monad and this answer shows that chain function in underscore.js library is not a monad (but comonad). And answer to this which is similar, shows that is monoid.
So, is jQuery a monad?
A monad is a way of composing functions that require context in addition to the return value, such as computation, branching, or I/O. Monads type lift, flatten and map so that the types line up for lifting functions a => M(b) , making them composable.
In terms of OO programming, a monad is an interface (or more likely a mixin), parameterized by a type, with two methods, return and bind that describe: How to inject a value to get a monadic value of that injected value type; How to use a function that makes a monadic value from a non-monadic one, on a monadic value.
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.
Most APIs do not satisify the monad laws. jQuery
is a large API
, so statistically, it is unlikely to be "accidentally" monadic. As a result I am pretty skeptical that the jQuery
API as a whole could satisfy the monad laws (i.e. that "jQuery is a monad").
This doesn't mean that a given (very restricted) subset might not satisfy them, but the API as a whole is likely to contain "unsafe" operations that would violate the laws when used, breaking the abstraction.
Since no one seems to have offered evidence that the API in whole or part satisifies the laws, I suggest we should assume it does not, until evidence is provided.
It must be shown:
return
(lifting a value into the jQuery monad)?bind
, for gluing computations together?And then, what law violations are possible given the rest of the jQuery API? Can I, for example, break the bind
by calling one of the other API functions?
References:
I think you're referring to jQuery's implicit looping behavior. In that respect jQuery is similar to working in the list monad, where chaining is equivalent to bind
, and wrapping an element in $()
is akin to return
(I guess).
So where with jquery you might append a new list element to a bunch of divs of lists with:
$('div').children().append("<li>New list element</li>");
...in haskell you might have:
appendToEachList divs = divs >>= children >>= append "<li>New list element</li>"
The above is from memory and should be considered pseudocode nonsense.
Anyway, I think it would be a stretch to say "jQuery is a Monad".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With