Created
December 7, 2013 06:03
-
-
Save ympbyc/7837801 to your computer and use it in GitHub Desktop.
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
/* | |
* 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