Created
June 27, 2021 14:12
-
-
Save kraftdorian/f6caa56c474b00fdeec8d115d6f0c78e to your computer and use it in GitHub Desktop.
My first attempt to understand Monads in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Heavily based on this great article by Eric Elliott: | |
// https://medium.com/javascript-scene/javascript-monads-made-simple-7856be57bfe8 | |
const main1 = () => { | |
const compose = (f, g) => (x) => f(g(x)); | |
// g :: Integer -> [Integer] | |
const g = (a) => Array.of(a); | |
// f :: [Integer] -> Bool | |
const f = (b) => b.reduce((x, y) => x + y) > 0; | |
// h :: Integer -> Bool | |
const h = (x) => compose(f, g)(x); | |
const result = h(3); // f(g(3)) -> Array.of(3) -> [3].reduce((x, y) => x + y) > 0 | |
console.log(result); // true | |
}; | |
const main2 = () => { | |
// Identity monad | |
const Id = value => ({ | |
map: f => Id.of(f(value)), | |
chain: f => f(value), | |
toString: () => `Id(${value})` | |
}); | |
Id.of = Id; | |
const g = n => Id(n + 1); | |
const f = n => Id(n * 2); | |
const result = Id(20).chain(f).chain(g).toString(); // 20 * 2 -> 40 + 1 | |
console.log(result); // Id(41) | |
}; | |
main1(); | |
main2(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment