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:
“It is a very true and expressive phrase, He looked daggers at me, for the first pattern and prototype of all daggers must have been a glance of the eye.... It is wonderful how we get about the streets without being wounded by these delicate and glancing weapons, a man can so nimbly whip out his rapier, or without being noticed carry it unsheathed. Yet it is rare that one gets seriously looked at.”
—Henry David Thoreau (18171862)