WolframLang: Change Expression by Pattern
Intro to Expression Transformation by Rules
The following functions transform expression by a rule or list of rules.
Pattern Matching and Expression Tree Depth Level Spec
One important aspect is what level of tree depth to match a pattern.
It has effect on the match when the pattern itself is a nested expression.
Replace First Occurrence or All Occurrences
Both
Replace
and
ReplaceAll
replace all occurrences. (the “All” in “ReplaceAll” refers to levels.)
Some functions have a optional parameter that specify doing just the first n occurrences.
e.g.
Cases
.
〔see WolframLang: Filter List〕
Function that Transform Expression by Pattern
ReplaceAll[expr, rules]
ReplaceRepeated[expr, rules]
-
🔸 SHORT SYNTAX:
expr //. rules
repeatedly performs
ReplaceAll
until expr no longer changes.ReplaceRepeated [ { 2, 3, 4, {99, 6}}, x_Integer?(Function[ UnsameQ[ Mod[ #, 5 ], 0 ] ]) :> x + 1 ] (* {5, 5, 5, {100, 10}} *)
Replace with Depth Level Restriction
Replace[expr, rules, levelSpec]
-
transform expression but matching only at levelSpec.
By default, it is level
{0}
, meaning whole expression. 〔see WolframLang: Pattern Matching and Level Spec〕(* importance of level spec for non-flat patterns *) (* match at level 1 to 99 *) Replace[ {1, {2, {3, {4}}}}, {_Integer, {_Integer}} -> x, {1,99}] (* {1, {2, x}} *) (* match at level 1 only *) Replace[ {1, {2, {3, {4}}}}, {_Integer, {_Integer}} -> x, {1}] (* {1, {2, {3, {4}}}} *) (* no match found *)
ReplaceList[expr, rules]
-
- Transform entire expression and return a list of steps of each rule applied.
- 🛑 WARNING: match against entire expression, not parts of it.
Replace at Specific Position
ReplaceAt[expr, rules, n]
-
transforms expr by replacing nth element using rules
ReplaceAt[expr, rules, positionSpec]
-
transforms expr by replacing the particular positions using rules