Tuesday, February 26th, 2008

JavaScript Functional Pattern Matching

Category: JavaScript

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

  1. function fact (n) {
  2.   return m.match(n,
  3.   [
  4.     [    0  , function ( ) { return 1                    }],
  5.     [ _("n"), function (a) { return (a.n * fact(a.n -1)) }]
  6.   ]);
  7. }

or working with complex structures:

javascript

  1. function go_deep(ob) {
  2.   return m.match(ob,
  3.   [
  4.     [{foo:{bar:{baz:'foo'}}, baz:_('b')}, function (a) { return a.b  }],
  5.     [_('_')                             , function ( ) { return null }]
  6.   ]);
  7. }

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 :)”

Posted by Dion Almaer at 7:21 am
Comment here

+++--
3.3 rating from 15 votes

Comments Here »

Comments feed TrackBack URI

Leave a comment

You must be logged in to post a comment.