Skip to content

Instantly share code, notes, and snippets.

@andyhd
Created January 12, 2012 16:07
Show Gist options
  • Save andyhd/1601336 to your computer and use it in GitHub Desktop.
Save andyhd/1601336 to your computer and use it in GitHub Desktop.
Functional pattern matching (sort of) with Javascript
function when(x) {
return function () {
for (var i in arguments) {
var result = arguments[i](x);
if (result !== false) {
return result;
}
}
throw "No patterns matched when(" + x + ")";
};
}
function match(pattern) {
return function (then) {
return function (x) {
var match = pattern === "*" ? true : pattern(x);
return match !== false ? then(match) : false;
}
}
}
function isZero(n) { return n === 0; }
function nonZero(n) { var i = parseInt(n); return i > 0 ? i : false; }
var fact = function (n) {
return when(n)(
match(isZero)(function () { return 1; }),
match(nonZero)(function (n) { return n * fact(n - 1); })
);
}
console.log(fact(10));
@0atman
Copy link

0atman commented Jan 13, 2012

Nice!

@andyhd
Copy link
Author

andyhd commented Jan 13, 2012

Falsy values handled more cleanly now, but there's still a lot of room for improvement, especially around using "*" for matching anything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment