Skip to content

Instantly share code, notes, and snippets.

@ympbyc
Created December 7, 2013 06:03
Show Gist options
  • Save ympbyc/7837801 to your computer and use it in GitHub Desktop.
Save ympbyc/7837801 to your computer and use it in GitHub Desktop.
/*
* thunk ~= promise
* thunkのforceは別スレッド (投機的実行)
*/
function Thunk (thunk) {
this.thunk = thunk;
this.val = null;
this.ff = [];
}
Thunk.prototype.done = function (f) {
this.ff.push(f);
if (this.val) this.exec();
};
Thunk.prototype.exec = function () {
var v = this.val;
if (v) this.ff.map(function (f) { f(v); });
this.ff = [];
};
Thunk.prototype.resolve = function () {
if (this.val) return null;
this.val = this.thunk();
this.exec();
return null;
};
function add (f, x, y) {
x.done(function (x) {
y.done(function (y) {
f(x + y);
})});
}
var a = Thunk(function () { return 5; });
var b = Thunk(function () { return 4; });
spawn(function () { a.resolve(); });
spawn(function () { b.resolve(); });
add(halt, a, b);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment