Tuesday, February 26th, 2008
JavaScript Functional Pattern Matching
<p>Adrien Friggeri has been playing with pattern matching in JavaScript a la functional programming.Take a look at the examples such as writing a factorial via matching:
-
-
function fact (n) {
-
return m.match(n,
-
[
-
[ 0 , function ( ) { return 1 }],
-
[ _("n"), function (a) { return (a.n * fact(a.n -1)) }]
-
]);
-
}
-
or working with complex structures:
-
-
function go_deep(ob) {
-
return m.match(ob,
-
[
-
[{foo:{bar:{baz:'foo'}}, baz:_('b')}, function (a) { return a.b }],
-
[_('_') , function ( ) { return null }]
-
]);
-
}
-
When is this useful? Adrien is "sure some genius out there would find a cool use for it : dom navigation ? input validation ? json validation ? you name it :)"
Related Content:











Leave a comment