Skip to content

Instantly share code, notes, and snippets.

@dypsilon
Created August 8, 2016 09:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dypsilon/23f75c6f458b65038a660352c8544dcb to your computer and use it in GitHub Desktop.
Save dypsilon/23f75c6f458b65038a660352c8544dcb to your computer and use it in GitHub Desktop.
Eager Continuation in JavaScript
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;
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);
@SimonRichardson
Copy link

SimonRichardson commented Aug 9, 2016

👍 https://github.com/fantasyland/fantasy-promises/blob/master/src/promise.js#L19

This is how fantasy-promises are implemented :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment