WolframLang: Pattern Matching
Pattern matching is a core mechanism how WolframLang does computation. WolframLang is a term-rewriting system, meaning, it transform expressions according to rules until no rule matches.
A rule is a pair of values that looks like this:
left-hand-side → right-hand-side.
The left-hand-side is usually a pattern. [see Pattern Syntax]
For the transformation, there local and global transformations:
- Local transformation: Functions that take a expression and list of rules, and return a new expression.
- Global transformation: A set a rules defined globally. Evaluation of any expression uses these rules to transform expression. (this is done by Set and SetDelayed)
Functions that Transform Expression by Rules
The following functions take a expression and a rule or list of rules, and transform expression accordingly.
expr /. rules)
- Replace expr by transformation rules rules.
- rules can be a single rule or a list of rules.
Note: this is the most frequently used.ReplaceAll
expr //. rules)
repeatedly performs replacements until expr no longer changes.
Replace[expr, rules, levelSpec]
- applies a rule or list of rules in an attempt to transform the entire expression, at levelSpec Replace
ReplaceAt[expr, rules, positionSpec]
- transforms expr by replacing the particular positions using rules ReplaceAt
- transform the entire expression by applying a rule or list of rules in all possible ways, and returns a list of the results obtained. ReplaceList