The Ashes

Technology, Science and other news
April 25, 2009

myPatterns: XPath / RegEx for JS Objects

Posted by : admin
Filed under : General

Nic Volanschi pointed us to myPatterns:

myPatterns is a new library adding custom notations for data structures in JS (and also C). It’s really useful for writing elegant programs using general pattern matching.

To explain myPatterns, let’s introduce a standard JavaScript object:

PLAIN TEXT
JavaScript:

  1. {
  2.   name: { firstname: “John”, lastname: “Smith” },
  3.   children: [
  4.     { firstname: “Eric”, gender: “male”, born: 1991 },
  5.     { firstname: “Deborah”, gender: “female”, born: 1996 }
  6.   ]
  7. }

Using myPattern, you can write a test to check if this object represents a person whose first child is a boy 18 years old:

PLAIN TEXT
JavaScript:

  1. (s = match(x, “{name:{lastname: %l}, children:[{gender: ‘male’, born: %b} | %x]}”))
  2. && new Date().getFullYear() – s.b == 18

The website explains the pattern above:

In the above, the match() statement both checks whether the object has a certain form (e.g. that the children field is an array containing a first element of a given form), and returns a “substitution” object s having the following value: {l: “Smith”, b: 1991, x: [ {firstname: “Deborah” , born: 1996} ]}.

Furthermore, using your own notations, you could write the same condition more concisely, and with your own personal touch, for example:

JavaScript:

  1. s = match(x, “<%first ~ %last: [boy(18) | %rest]>”)

In the above, the object is noted in a more concise way, and the age of the first son is directly specified in the pattern, as if it was stored in the object, taking advantage of active patterns to compute the age on the fly.

Neat!

Tags :

No Comments

(required)
(will not be published) (required)
(opitional)

cciash.com EN ES IT DE PT CZ FR RU
October 2018
M T W T F S S
« Sep    
1234567
891011121314
15161718192021
22232425262728
293031  

Pages

Categories

Resources

There are many online poker site where you can play but at poker.hk you can play the poker games with all the knowledge you need related to the game with the poker school available in both the English and Chinese language.

Super Casino

Now you can bet on any sports and any sporting events from all the comfort from your home. Bet770 allows you to bet on any events and match with in just 3 clicks. They also offers great odds on football betting for every premier and champions league match. Get £50 free in bets when you register.

Bingo770, offering best online bingo games with £7.70 free no deposit Bonus!