Created
April 9, 2011 09:13
-
-
Save mishoo/911261 to your computer and use it in GitHub Desktop.
amb 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
// 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