Created
June 4, 2015 04:24
-
-
Save tel/9a34caf0b6e38cba6772 to your computer and use it in GitHub Desktop.
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
function Cont(contHandler) { | |
this.contHandler = contHandler; | |
}; | |
Cont.unit = function(value) { | |
return new Cont(function (continue) { return continue(value); }); | |
}; | |
Cont.prototype.run = function(resume) { | |
return this.contHandler(resume); | |
}; | |
Cont.prototype.escape = function() { | |
return this.run(function(x) { return x; }); | |
}; | |
Cont.prototype.doNothing = function () { | |
var self = this; | |
return new Cont(function(resume) { | |
return self.run(function(value) { | |
return resume(value); | |
}); | |
}); | |
}; | |
Cont.prototype.doNothing = function () { | |
var self = this; | |
return new Cont(function(resume) { return self.run(resume); }); | |
}; | |
Cont.prototype.bind = function (transform) { | |
var self = this; | |
return new Cont(function(resume) { | |
return self.run(function (value) { | |
return transform(value).run(resume); | |
}); | |
}); | |
}; | |
// > Cont.unit(3).bind(function(x) { return Cont.unit(4).bind(function (y) { return Cont.unit(x + y); }); }).escape(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment