Pattern Matching - Pattern Matching in Mathematica

Pattern Matching in Mathematica

In Mathematica, the only structure that exists is the tree, which is populated by symbols. In the Haskell syntax used thus far, this could be defined as

data SymbolTree = Symbol String

An example tree could then look like

Symbol "a", Symbol "c"

In the traditional, more suitable syntax, the symbols are written as they are and the levels of the tree are represented using, so that for instance a is a tree with a as the parent, and b and c as the children.

A pattern in Mathematica involves putting "_" at positions in that tree. For instance, the pattern

A

will match elements such as A, A, or more generally A where x is any entity. In this case, A is the concrete element, while _ denotes the piece of tree that can be varied. A symbol prepended to _ binds the match to that variable name while a symbol appended to _ restricts the matches to nodes of that symbol.

The Mathematica function Cases filters elements of the first argument that match the pattern in the second argument:

Cases, b, a, b}, a ]

evaluates to

{a, a}

Pattern matching applies to the structure of expressions. In the example below,

Cases, a, a, d], a, de, a, d, e]}, a, _] ]

returns

{a,d], a,de}

because only these elements will match the pattern a,_] above.

In Mathematica, it is also possible to extract structures as they are created in the course of computation, regardless of how or where they appear. The function Trace can be used to monitor a computation, and return the elements that arise which match a pattern. For example, we can define the Fibonacci sequence as

fib:=1 fib:= fib + fib

Then, we can ask the question: Given fib, what is the sequence of recursive Fibonacci calls?

Trace, fib]

returns a structure that represents the occurrences of the pattern fib in the computational structure:

{fib,{fib,{fib},{fib}},{fib}}

Read more about this topic:  Pattern Matching

Famous quotes containing the word pattern:

    No, I will be the pattern of all patience,
    I will say nothing.
    William Shakespeare (1564–1616)