Ajax Blog


JavaScript Functional Pattern Matching

Posted in Ajax News by Dion Almaer on the February 26th, 2008

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:

JAVASCRIPT:
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:

JAVASCRIPT:
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 :)"

Source: Ajaxian
Original Article: http://feeds.feedburner.com/~r/ajaxian/~3/241458625/javascript-functional-pattern-matching

Comments are closed.