← Back to context

Comment by anon291

21 days ago

Because you're not used to abstract algebra. JavaScript arrays form a monad with flatmap as the join operator. There are multiple ways to make a monad with list like structures.

And you are correct. Monads have nothing to do with sequencing (I mean any more than any other non commutative operator -- remember x^2 is not the same as 2^x)

Haskell handles sequencing by reducing to weak head normal form which is controlled by case matching. There is no connection to monads in general. The IO monad uses case matching in its implementation of flatmap to achieve a sensible ordering.

As for JavaScript flat map, a.flatMap(b).flatMap(c) is the same as a.flatMap(function (x) { return b(x).flatMap(c);}).

This is the same as promises: a.then(b).then(c) is the same as a.then(function (x) { return b(x).then(c)}).

Literally everything for which this is true forms a monad and the monad laws apply.

Nota bene, then is not a monad because the implementation of then implies map is isomorphic to flatmap. This is because `then` turns the return value of a callback into a flat promise, even if the callback itself returns a promise.

That is to say, then checks the type of the return value and then takes on map or flatmap behavior depending on whether the return value of the callback is a Promise or not.

OK, so the defining characteristic of a monad M is that:

a.M(b).M(c) = a.M(function(x){return b(x).M(c)})

So the next question is: why should I care about that pattern in particular?

  • You don't? There's nothing special about monads. I don't know why everyone cares so much about them.

    There are a few generic transforms you can use to avoid boilerplate. You can reason about your code more easily if your monad follows all the monad laws. But let's be real.. most programmers don't know how to reason about their code anyway, so it's a moot point