Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Monad chain does exist now in JS #242

Open
LLyaudet opened this issue Mar 24, 2023 · 3 comments
Open

Monad chain does exist now in JS #242

LLyaudet opened this issue Mar 24, 2023 · 3 comments

Comments

@LLyaudet
Copy link

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

@laurentpayot
Copy link

Hi Laurent, if I’m right chaining promises with .then() in JS was already monadic 😉

@LLyaudet
Copy link
Author

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 ?

@laurentpayot
Copy link

laurentpayot commented Mar 28, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants