Open LLyaudet opened 1 year ago
Hi Laurent, if I’m right chaining promises with .then()
in JS was already monadic :wink:
Hello Laurent,
Thanks :) I'm not new to (partly functional - pun intended) JS programming ;). But I'm new to the concept of Monad in functional programming and it was not immediate for me that the explanation given in this repo applies also to JS Promises.
Monad
A monad is an object with of and chain functions. chain is like map except it un-nests the resulting nested object.
// Implementation
Array.prototype.chain = function (f) {
return this.reduce((acc, it) => acc.concat(f(it)), [])
}
// Usage
Array.of('cat,dog', 'fish,bird').chain((a) => a.split(',')) // ['cat', 'dog', 'fish', 'bird']
// Contrast to map
Array.of('cat,dog', 'fish,bird').map((a) => a.split(',')) // [['cat', 'dog'], ['fish', 'bird']]
of is also known as return in other functional languages. chain is also known as flatmap and bind in other languages.
Now I see that new Promise()
has the role of of
and that indeed .then()
acts like chain()
.
But now I also find it strange that Array
was chosen as an example.
Was it because it could illustrate more explicitely the unnesting ?
But now I also find it strange that Array was chosen as an example. Was it because it could illustrate more explicitely the unnesting ?
I don’t know :thinking: Maybe JS was chosen for this repository because it is a lingua franca that everyone knows enough to understand FP concepts implemented in it, whatever your language background is. In the same way arrays-like structures are implemented in most languages and most people know them, unlike promises.
Hello,
I just wanted to say that flatMap is part of JS and widely supported now :) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap
Have a nice day, best regards, Laurent Lyaudet