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:
“The real trouble about women is that they must always go on trying to adapt themselves to mens theories of women, as they always have done. When a woman is thoroughly herself, she is being what her type of man wants her to be. When a woman is hysterical its because she doesnt quite know what to be, which pattern to follow, which mans picture of woman to live up to.”
—D.H. (David Herbert)