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

- Syntax that specify rules.
- Syntax that specify pattern for the left-hand-side of rules. [see Pattern Syntax]

For the transformation, you need 2 things:

- Local transformation: Functions that take a expression and list of rules, and return a new expression.
- Global transformation: A way to set a rule globally. Evaluation of any expression will use the rule to transform expression. (this is done by Set and SetDelayed)

## 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.)ReplaceAll[ {a, b, c} , x_ -> x+1] === {1 + a, 1 + b, 1 + c}

`RuleDelayed[`

`lhs`,`rhs`]- (Short syntax:

)`lhs`:>`rhs`

Same as

RuleDelayed`Rule`

, but`rhs`is evaluated at the time the transformation happens.

## 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 - Replace
`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