Function Repository Resource:

SetByRules

Source Notebook

Use rules to make assignments

Contributed by: Yong-an Lu

ResourceFunction["SetByRules"][rules]

sets left sides of rules to their right sides.

ResourceFunction["SetByRules"][rules,f]

assigns using functionf to resolve conflicts in case of identical left hand sides.

Details and Options

ResourceFunction["SetByRules"][rules] is effectively equivalent to ResourceFunction["SetByRules"][rules,First].
If rules is a nested list, it will be flattened first.
Unlike Merge, the functionf is applied to rules instead of their values.

Examples

Basic Examples (3) 

Perform assignments according to given rules:

In[1]:=
ResourceFunction["SetByRules"][{x -> 2, f[x_] :> x^2}]
Out[1]=
In[2]:=
f[x]
Out[2]=

Apply the first rule in case of conflict:

In[3]:=
ResourceFunction["SetByRules"][{n -> 1, n -> 2, n -> 3}]
Out[3]=
In[4]:=
n
Out[4]=

Specify how to resolve a conflict:

In[5]:=
ResourceFunction["SetByRules"][{n -> 1, n -> 2, n -> 3}, Last]
Out[5]=
In[6]:=
n
Out[6]=

Scope (1) 

Rules are not distinguished by pattern parameters:

In[7]:=
ResourceFunction[
 "SetByRules"][{g[x_] :> x, g[1] -> -1, g[y_] :> y + 1, g[z_] /; z > 0 :> Sqrt[z]}]
Out[7]=
In[8]:=
Definition[g]
Out[8]=

Applications (1) 

Assignment immediately after solving the equation:

In[9]:=
Solve[{a^2 + b^2 == c^2, a + b + c == 1000, 0 < a < b < c}, {a, b, c},
   Integers] // ResourceFunction["SetByRules"]
Out[9]=
In[10]:=
a b c
Out[10]=

Possible Issues (1) 

If the conflict is not resolved effectively, then a warning will be generated and the conflict will be automatically resolved:

In[11]:=
ResourceFunction["SetByRules"][{n -> 1, n -> 2, n -> 3}, Identity]
Out[11]=

Publisher

Yong-an Lu

Version History

  • 1.0.0 – 14 October 2019

License Information