Skip to content

Instantly share code, notes, and snippets.

@mishoo
Created April 9, 2011 09:13
Show Gist options
  • Save mishoo/911261 to your computer and use it in GitHub Desktop.
Save mishoo/911261 to your computer and use it in GitHub Desktop.
amb in javascript
// following https://gist.github.com/911094
function amb_run(program, failure_value) {
var index = 0, steps = [];
while (true) try {
return program(amb, fail);
} catch(ex) {
if (ex !== fail) throw ex;
for (var i = steps.length; --i >= 0;) {
var a = steps[i];
if (++a[0] < a[1]) break;
}
if (i < 0) return failure_value;
index = 0;
steps.length = i + 1;
}
function amb(values) {
if (values.length == 0) fail();
if (index == steps.length)
steps[index] = [ 0 ];
steps[index][1] = values.length;
return values[steps[index++][0]];
}
function fail() { throw fail }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment