Created
August 8, 2016 09:27
-
-
Save dypsilon/23f75c6f458b65038a660352c8544dcb to your computer and use it in GitHub Desktop.
Eager Continuation 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
const {tagged} = require('daggy'); | |
let Continuation = tagged('x'); | |
Continuation.prototype.of = Continuation.of = x => { | |
return new Continuation((resolve) => resolve(x)); | |
} | |
Continuation.prototype.chain = function(f) { | |
return this.x(f); | |
}; | |
Continuation.prototype.inspect = function() { | |
return `Continuation(${this.x})`; | |
} | |
// derivations | |
Continuation.prototype.map = function(f) { | |
var m = this; | |
return m.chain(a => m.of(f(a))); | |
} | |
Continuation.prototype.ap = function(m) { | |
return this.chain(f => m.map(f)); | |
} | |
module.exports = Continuation; |
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
const Cont = require('../lib/continuation'); | |
// pointed version | |
const c = Cont.of(5) // initial value | |
.chain((x) => { | |
return Cont.of(x + 5); // synchronous computation | |
}) | |
.chain((x) => { // async computation | |
return new Cont((resolve) => { | |
setTimeout(() => resolve(x + 15), 500); | |
}); | |
}); | |
Cont.of(console.log).ap(c); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍 https://github.com/fantasyland/fantasy-promises/blob/master/src/promise.js#L19
This is how fantasy-promises are implemented :)