Skip to content

Instantly share code, notes, and snippets.

@justinvdm
Last active January 2, 2018 07:10
Show Gist options
  • Save justinvdm/06117035c93c51a719ed3c3515031632 to your computer and use it in GitHub Desktop.
Save justinvdm/06117035c93c51a719ed3c3515031632 to your computer and use it in GitHub Desktop.
Cont monad in javascript with flowtype
// @flow
type Cont<R, A> = (A => R) => R;
const ret = <R, A>(a: A): Cont<R, A> =>
k => k(a);
const bind = <R, A, B>(cont: Cont<R, A>, fn: A => Cont<R, B>): Cont<R, B> =>
k => cont(a => fn(a)(k));
const add = <R>(a: number, b: number): Cont<R, number> => ret(a + b);
const sqr = <R>(a: number): Cont<R, number> => ret(a * a);
const pythag = <R>(a: number, b: number): Cont<R, number> =>
bind(sqr(a), aSqrd =>
bind(sqr(b), bSqrd =>
add(aSqrd, bSqrd)));
const callCC = <R, A, B>(fn: (A => Cont<R, B>) => Cont<R, A>): Cont<R, A> =>
k => fn(a => _ => k(a))(k);
pythag(2, 3)(console.log);
// `() => ret(25)` should never be called
const quux = callCC(cc =>
bind(cc(5), () =>
ret(25)))
quux(console.log);
[ignore]
[include]
[libs]
[lints]
[options]
[strict]
{
"name": "flow-cont-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-cont-monad",
"version": "1.0.0",
"description": "",
"main": "+flow-cont-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