Skip to content

Instantly share code, notes, and snippets.

@justinvdm
Last active January 1, 2018 15:38
Show Gist options
  • Save justinvdm/caff60337c2bdecb0e73405e75837e4b to your computer and use it in GitHub Desktop.
Save justinvdm/caff60337c2bdecb0e73405e75837e4b to your computer and use it in GitHub Desktop.
// @flow
type Nothing = {|
type: 'nothing'
|};
type Just<A> = {|
type: 'just',
value: A
|};
type Maybe<A> = Just<A> | Nothing;
const just = <A>(value: A): Just<A> => ({
type: 'just',
value
});
const nothing: Nothing = {
type: 'nothing',
};
const ret = <A>(a: A): Maybe<A> => just(a);
const bind = <A, B>(a: Maybe<A>, fn: (A => Maybe<B>)): Maybe<B> =>
a.type === 'just'
? fn(a.value)
: nothing;
const evenOnly = (a: number): Maybe<number> =>
a % 2 === 0
? just(a)
: nothing;
const dbl = (a: number): Maybe<number> =>
just(a * 2);
console.log(bind(bind(ret(22), evenOnly), dbl)); // ret 22 >>= evenOnly >>= dbl
console.log(bind(bind(ret(23), evenOnly), dbl)); // ret 23 >>= evenOnly >>= dbl
[ignore]
[include]
[libs]
[lints]
[options]
[strict]
{
"name": "flow-maybe-monad",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"babylon": {
"version": "6.18.0",
"resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz",
"integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==",
"dev": true
},
"flow-bin": {
"version": "0.62.0",
"resolved": "https://registry.npmjs.org/flow-bin/-/flow-bin-0.62.0.tgz",
"integrity": "sha1-FLymaabj+VwLwMLR61XsTpjLHYM=",
"dev": true
},
"flow-remove-types": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/flow-remove-types/-/flow-remove-types-1.2.3.tgz",
"integrity": "sha512-ypq/U3V+t9atYiOuSJd40tekCra03EHKoRsiK/wXGrsZimuum0kdwVY7Yv0HTaoXgHW1WiayomYd+Q3kkvPl9Q==",
"dev": true,
"requires": {
"babylon": "6.18.0",
"vlq": "0.2.3"
}
},
"vlq": {
"version": "0.2.3",
"resolved": "https://registry.npmjs.org/vlq/-/vlq-0.2.3.tgz",
"integrity": "sha512-DRibZL6DsNhIgYQ+wNdWDL2SL3bKPlVrRiBqV5yuMm++op8W4kGFtaQfCs4KEJn0wBZcHVHJ3eoywX8983k1ow==",
"dev": true
}
}
}
{
"name": "flow-maybe-monad",
"version": "1.0.0",
"description": "",
"main": "+flow-maybe-monad.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"flow-bin": "^0.62.0",
"flow-remove-types": "^1.2.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment