Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Replace the part of an expression specified by position via a rule
| ResourceFunction["ReplacePartWith"][expr,rule,pos] applies a replacement rule to the part of expr at position pos. | 
Replace parts 1, 3 and 4 with the rule c→e:
| In[1]:= | ![ResourceFunction["ReplacePartWith"][{c, b, c, d}, c -> e, {{1}, {3}, {4}}]](https://www.wolframcloud.com/obj/resourcesystem/images/85e/85e04784-e150-4580-bbc7-a4ac8d8fc3ff/6ecb2900e2487cc6.png) | 
| Out[1]= |  | 
ReplacePartWith takes lists of positions in the same form as generated by Position:
| In[2]:= | ![Position[{a, b, x, c, d, x, e}, x]](https://www.wolframcloud.com/obj/resourcesystem/images/85e/85e04784-e150-4580-bbc7-a4ac8d8fc3ff/4295d9a4f27438d3.png) | 
| Out[2]= |  | 
| In[3]:= | ![ResourceFunction[
 "ReplacePartWith"][{a, b, x, c, d, x, e}, {x -> yy}, {{3}, {6}}]](https://www.wolframcloud.com/obj/resourcesystem/images/85e/85e04784-e150-4580-bbc7-a4ac8d8fc3ff/1bc561645e2b24d4.png) | 
| Out[3]= |  | 
ReplacePart replaces parts of an expression. Exactly what the part is replaced with is specified in advance:
| In[4]:= | ![ReplacePart[{c, b, c, d}, {1 -> e, 2 -> f, 3 -> g}]](https://www.wolframcloud.com/obj/resourcesystem/images/85e/85e04784-e150-4580-bbc7-a4ac8d8fc3ff/5f2b0cd162f5e997.png) | 
| Out[4]= |  | 
ReplacePartWith replaces parts of an expression, and what is replaced is determined by the applied rule:
| In[5]:= | ![ResourceFunction["ReplacePartWith"][{c, b, c, d}, c -> e, {{1}, {3}, {4}}]](https://www.wolframcloud.com/obj/resourcesystem/images/85e/85e04784-e150-4580-bbc7-a4ac8d8fc3ff/28e561e5fde6e682.png) | 
| Out[5]= |  | 
Replacing an empty list of positions does not change the expression:
| In[6]:= | ![ResourceFunction["ReplacePartWith"][h[a, b], _ -> x, {}]](https://www.wolframcloud.com/obj/resourcesystem/images/85e/85e04784-e150-4580-bbc7-a4ac8d8fc3ff/49a175af57ab574f.png) | 
| Out[6]= |  | 
Position {} corresponds to the whole expression:
| In[7]:= | ![ResourceFunction["ReplacePartWith"][h[a, b], _ -> x, {{}}]](https://www.wolframcloud.com/obj/resourcesystem/images/85e/85e04784-e150-4580-bbc7-a4ac8d8fc3ff/4cbe4d9ee031e1f3.png) | 
| Out[7]= |  | 
This work is licensed under a Creative Commons Attribution 4.0 International License