Monday, January 2, 2012

Predicates, Tests and Test Patterns: Introduction and Significance

The Importance of Predicates

In his excellent Mathematica Cookbook (p. 149), Sal Mangano said about using a predicate:

"This is a powerful construct because it extends the degree of control over the matching process to any criteria Mathematica can compute." 

Mangone's example used a predicate to further qualify a Pattern (see Pattern Assignment, in Assignment in this book), which alone is a powerful device, but his is a general comment about predicates in a language as flexible as Mathematica's and when Mathematica is considered as a technical computing universe containing, for instance, curated scientific and financial data, the ability to import web pages, and a universal representation ("everything is an expression") for diverse data such as graphics, sound, and images.

In logic, a predicate is a set whose elements can be evaluated as True or False, or more simply, a predicate is a test of something that is either True or False. They can be simple or complex. Predicates are very handy in Mathematica, since it is quite common to apply conditions to lists or expressions, or to test elements of lists or expressions. Predicates are an implicit If test implemented in an intuitively useful way. John Gray notes that predicates are also a way of constructing data types, and interestingly, that John von Neumann based a version of set theory on predicates (Mastering Mathematica, 2nd ed., p 242).

Most of Mathematica's built-in predicates have a "Q" as their suffix, signifying that they ask a question. They are discussed in guide/TestingExpressions. Predicates are designed to return True if they exactly match a pattern and False if there is no precise match.

A precise match means that built-in predicates have subtle differences, e.g. Equal and SameQ, NumberQ and NumericQ, VectorQ, MatrixQ and ArrayQ. And capturing what we wish to be True in our own predicates can require some tinkering (see this post).

Predicates without a Q in their name are listed here.

Let's look at Mathematica's built-in predicates , and then we'll make our own. The new-in-10 function Multicolumn produces a nicely-formatted table easier than using Partition and TableForm.

Names@"*Q" // Multicolumn[#,5]&



We'll take a look at how to use Mathematica's Predicates in Part 2.

No comments:

Post a Comment