Created
January 12, 2012 16:07
-
-
Save andyhd/1601336 to your computer and use it in GitHub Desktop.
Functional pattern matching (sort of) with 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
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)); |
Nice!
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
Works, but needs tidying up. If the pattern matches, but the match is falsy, the "then" function won't be executed. If the "then" function returns a falsy value, then the next pattern will be tested. Bleh.