Skip to content

Instantly share code, notes, and snippets.

@supasympa
Last active August 8, 2019 11:35
Show Gist options
  • Save supasympa/b02fe86eee9e2183c1fb1795f357d123 to your computer and use it in GitHub Desktop.
Save supasympa/b02fe86eee9e2183c1fb1795f357d123 to your computer and use it in GitHub Desktop.
Monad example.
// https://hackernoon.com/functional-javascript-functors-monads-and-promises-679ce2ab8abe
const Thing = value => ({
value,
map: morphism => Thing(morphism(value)),
flatMap: morphism => morphism(value)
})
const thing1 = Thing(1) //=> Thing (1)
const thing2 = thing1.flatMap(x => Thing(x + 1)) //=> Thing (2)
/*
Sometimes functions return a value already wrapped. This could be inconvenient to use with a Functor because it will re-wrap the Functor in another Functor.
const getThing = () => Thing(2)const thing1 = Thing(1)thing1.map(getThing) //=> Thing (Thing ("Thing 2"))
This behavior is identical to Array's behavior.
const doSomething = x => [x, x + 100]
const list = [1, 2, 3]list.map(doSomething) //=> [[1, 101], [2, 102], [3, 103]]
*/
/*
A Functor is something that is Mappable or something that can be mapped between objects in a Category.
A Monad is similar to a Functor, but is Flat Mappable between Categories.
flatMap is similar to map, but yields control of the wrapping of the return type to the mapping function.
A Promise breaks the Functor and Monad laws, but still has a lot of similarities. Same same but different.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment