Monday, January 2, 2012

Assignment to a Pattern


I'll use a couple of examples on searching Strings from Sal Mangano's excellent Mathematica Cookbook to show how to use Pattern Assignment. First, it's simple enough to search some Strings for those that are numbers:

StringMatchQ[{"12345", "2468", "abcde"}, NumberString]

{True, True, False}

But if you want to add a Predicate, you need another device such as naming a Pattern and using the name in the Predicate. This is an example of Pattern Assignment where the Pattern is named "m".

StringMatchQ[{"12345", "2468", "abcde"}, m : NumberString /; OddQ@FromDigits@m]

{True, False, False}

As Sal Mangone notes in his Mathematica Cookbook and I explore further in Predicates, Tests, and Test Patterns, adding a Predicate to a Pattern is a powerful device because we can include in the Predicate anything that Mathematica can compute. A Predicate can be a built-in one or one we construct, so the possibilities are truly limitless.

No comments:

Post a Comment