Hacker News new | ask | show | jobs
by aikah 3942 days ago
A concise and good explanation thanks.
1 comments

Note that the word "monad" itself refers just to the "shape" of the object (and some rules about that shape), not the functionality.

For example, an array can be a monad if we define a bind method as map + flatten

  Array.prototype.flatMap = function(f) {
    return _.flatten(this.map(f))
  }
which works like so:

  allArticles = authors.flatMap(author => author.articles);
return would be

  Array.of = function(val) { return [val]; }
The shape (type) is the same:

the promise's bind (then) method takes a function that takes a value and returns a promise, and returns another promise

the array's bind (flatMap) method takes a function that takes a value and returns an array, and returns another array

the promise's return (Promise.resolve) method takes a value and wraps it in a promise

the array's return (Array.of) method takes a value and wraps it in an array.

You can get the array method types (shapes) from the promise ones by replacing promise with array (if you decide to give the methods the same name).

The implemented functionality, however, is vastly different.