33

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?

Community
  • 1
  • 1
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • I don't know jQuery, so have limited ability to answer this but things [having co-monadic structure generally implies also having monadic structure][1] if you look at them the right way [1]: http://comonad.com/reader/2011/monads-from-comonads/ – Philip JF May 08 '12 at 11:10
  • 7
    Are you asking someone to show that the monad laws hold for the core of the jQuery API? – Don Stewart May 08 '12 at 11:45
  • "Monad" really describes a method (and a pattern of use) rather than a type. jQuery have a large number of methods, but none of them (AFAICT) conforms to the definition of monad. And that is a good thing! jQuery would just be more verbose and cumbersome if it was based on monadic chaining. – JacquesB Sep 20 '20 at 15:15

2 Answers2

32

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:

  • what jQuery operation corresponds to return (lifting a value into the jQuery monad)?
  • what jQuery operation corresponds to bind, for gluing computations together?
  • how do the left-, right- and associativity laws hold over those operations?

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:

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Don Stewart
  • 137,316
  • 36
  • 365
  • 468
12

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".

jberryman
  • 16,334
  • 5
  • 42
  • 83