Wolfram Research

Function Repository Resource:

MultiReplace (1.0.0) current version: 2.2.3 »

Source Notebook

ReplaceList with recursion

Contributed by: Nikolay Murzin

ResourceFunction["MultiReplace"][expr, rules]

return all possible subexpressions of expr after application of rules with information about each replacement.

Details and Options

ResourceFunction["MultiReplace"] returns association with keys containing rule index and position of a subexpression where the corresponding rule was applied
If one rule is given, keys contain positions only
Association values are results of applying ReplaceList at corresponding positions
ResourceFunction["MultiReplace"] takes the following options:
"OuterMatchPattern" _ what outer subexpressions are allowed
"InnerMatchPattern" _ what inner subexpressions are allowed
Heads True whether to include expression heads

Examples

Basic Examples (2) 

Apply a rule at each possible position of an expression:

In[1]:=
ResourceFunction["MultiReplace"][f[x, g[y]], a_ :> h[a]]
Out[1]=

Apply multiple rules:

In[2]:=
ResourceFunction["MultiReplace"][f[x, g[y]], {a_ :> h[a], b_ -> 1}]
Out[2]=

Options (3) 

OuterMatchPattern (1) 

Replace expressions with all outer subexpressions matching a given pattern:

In[3]:=
ResourceFunction["MultiReplace"][f[g[y]], a_ :> h[a], "OuterMatchPattern" -> Except[_g]]
Out[3]=

InnerMatchPattern (1) 

Replace expressions with all inner subexpressions matching a given pattern:

In[4]:=
ResourceFunction["MultiReplace"][f[x, g[y]], a_ :> h[a], "InnerMatchPattern" -> x | y]
Out[4]=

Heads (1) 

Ignore heads:

In[5]:=
ResourceFunction["MultiReplace"][f[x], a_ :> g[a], Heads -> False]
Out[5]=

Properties and Relations (1) 

Replacement is done in all possible ways similar to ReplaceList but at multiple positions:

In[6]:=
ReplaceList[{a, {b, c}}, {___, x_, ___} :> f[x]]
Out[6]=
In[7]:=
ResourceFunction["MultiReplace"][{a, {b, c}}, {___, x_, ___} :> f[x]]
Out[7]=

Version History

  • 2.2.3 – 05 January 2024
  • 2.2.2 – 27 September 2023
  • 2.2.1 – 22 February 2023
  • 2.2.0 – 03 February 2023
  • 2.1.0 – 15 June 2022
  • 2.0.0 – 01 February 2022
  • 1.0.0 – 08 November 2021

License Information