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 StringAn 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
Awill 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:
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
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:
Read more about this topic: Pattern Matching
Famous quotes containing the word pattern:
“Why it was that upon this beautiful feminine tissue, sensitive as gossamer, and practically blank as snow as yet, there should have been traced such a coarse pattern as it was doomed to receive; why so often the coarse appropriates the finer thus, the wrong man the woman, the wrong women the man, many years of analytical philosophy have failed to explain to our sense of order.”
—Thomas Hardy (18401928)