Function Repository Resource:

RuleReverse

Source Notebook

Reverse a Rule or RuleDelayed expression

Contributed by: Bradley Klee

ResourceFunction["RuleReverse"][rule]

returns rule after swapping the left- and right-hand sides, while keeping undetermined variables on the left-hand side.

ResourceFunction["RuleReverse"][rule,vars]

forces vars as undetermined variables on the left-hand side of the output.

Details

ResourceFunction["RuleReverse"] can be used on Rule and RuleDelayed expressions.

Examples

Basic Examples (2) 

Reverse a Rule object:

In[1]:=
ResourceFunction["RuleReverse"][f[x, y] -> g[a, b, c]]
Out[1]=

Reverse a RuleDelayed object:

In[2]:=
ResourceFunction["RuleReverse"][f[x_, y_] :> g[y]]
Out[2]=

Properties and Relations (3) 

Simple cases work like Reverse:

In[3]:=
SameQ[Reverse[#], ResourceFunction["RuleReverse"][#]] & /@ {x -> y, f[x] -> z, f[x, y] -> g[a, b, c]}
Out[3]=

With variable cases, blanks are forced to stay on the left-hand side:

In[4]:=
ResourceFunction[
   "RuleReverse"][#] & /@ {x_\[SmallCircle] y_ :> (y\[SmallCircle]x)\[SmallCircle]y, (y_\[SmallCircle]x_)\[SmallCircle]y_ :> x\[SmallCircle] y, f[x_, y_] :> g[y]}
Out[4]=

RuleReverse preserves types when possible:

In[5]:=
ResourceFunction["RuleReverse"][
 g[f[a_String, z_Integer], b_Other] :> {a, b, c2y__, z}]
Out[5]=

Possible Issues (2) 

Applying RuleReverse twice does not act as the identity when variables are projected out:

In[6]:=
expr = f[x_Type, y_Type] :> x;
Nest[ResourceFunction["RuleReverse"], expr, 2]
Out[7]=
In[8]:=
expr === %
Out[8]=

This issue can be fixed by setting the extra vars argument:

In[9]:=
Nest[ResourceFunction["RuleReverse"][#, {x_Type, y_Type}] &, f[x_Type, y_Type] :> x, 2]
Out[9]=
In[10]:=
expr === %
Out[10]=

If the right-hand side evaluates, repeated application might not act as the identity:

In[11]:=
With[{rule = f[x_] :> x + 1},
 SameQ[#, # /. rule /. ResourceFunction["RuleReverse"][rule]] & /@ {f[
    a], f[0]}]
Out[11]=

This issue can be fixed by adding a Hold to the right-hand side:

In[12]:=
With[{rule = f[x_] :> Hold[x + 1]},
 SameQ[#, # /. rule /. ResourceFunction["RuleReverse"][rule]] & /@ {f[
    0], f[a]}]
Out[12]=

Publisher

Brad Klee

Version History

  • 1.0.0 – 31 January 2022

License Information