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 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:

Rule Specification

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