-
-
Save amit08255/62ded90c0bc8448d6f442c861e84c882 to your computer and use it in GitHub Desktop.
Lazy Continuation Monad in JavaScript
This file contains hidden or 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('./lazy-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); | |
}); | |
}); | |
// we hold the whole computation in c right now | |
// nothing runs until we call run() | |
c.run(console.log); // result: 25 | |
// same thing with combinators pointfree style | |
const R = require('ramda'); | |
// lets extract some utility functions for readability | |
const syncMorphism = x => x + 5; | |
const syncComputation = x => Cont.of(x + 5); | |
const asyncComputation = x => { | |
return new Cont(resolve => setTimeout(() => resolve(x + 15), 500)); | |
} | |
// compose our program pipeline | |
const prog = R.pipe( | |
Cont.of, // lift the value into the continuation | |
R.map(syncMorphism), // lets test the map function | |
R.chain(syncComputation), | |
R.chain(asyncComputation) | |
) | |
// run the prog with the inital value of 5 | |
prog(5).run(console.log) // result: 30 |
This file contains hidden or 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
class Continuation { | |
constructor(x) { | |
this.x = x; | |
} | |
} | |
Continuation.prototype.of = Continuation.of = x => { | |
return new Continuation((resolve) => resolve(x)); | |
} | |
Continuation.prototype.chain = function(f) { | |
const x = this.x; | |
return new Continuation((resolve) => { | |
x((res) => f(res).x(res2 => resolve(res2))); | |
}); | |
}; | |
Continuation.prototype.run = 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment