WolframLang: Pattern Matching

By Xah Lee. Date: . Last updated: .

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 essentially a find/replace pair. The left-hand-side is a pattern, the right-hand-side is what it should change to.

For the rule specification, you need 2 things:

For the transformation, you need 2 things:

Specifying Rule

Rule[lhs,rhs]
(Short syntax: lhs -> rhs)

A syntax transformation rule that says left-hand-side lhs should be replaced by right-hand-side rhs

rhs is evaluated at the time this rule is evaluated. (in contrast to RuleDelayed, where rhs is evaluated at the time the transformation happens.)

Rule
ReplaceAll[ {a, b, c} , x_ -> x+1]
=== {1 + a, 1 + b, 1 + c}
RuleDelayed[lhs,rhs]
(Short syntax: lhs :> rhs)

Same as Rule, but rhs is evaluated at the time the transformation happens.

RuleDelayed

Pattern Syntax

Functions that Transform Expression by Rules

The following functions take a expression and a rule or list of rules, and transform expression accordingly.

ReplaceAll[expr, rules]
(Short syntax: 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
ReplaceRepeated[expr, rules]
(Short syntax: expr //. rules)
repeatedly performs replacements until expr no longer changes.
ReplaceRepeated
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
ReplaceList[expr, rules]
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

Most Frequently Used Functions that Take a Pattern

Pattern Matching

WolframLang in Depth

Basics

Comment, Print

String

Arithmetic

List

Expression, Atom, Head

Boolean

Conditional

Variable

Loop

Data Structure

Function

Pattern Matching

Advanced

Shell Tasks

Misc