Wolfram Research

Function Repository Resource:

ReplacePartWith

Source Notebook

Replace the part of an expression specified by position via a rule

Contributed by: Eric James Parfitt

ResourceFunction["ReplacePartWith"][expr,rule,pos]

applies a replacement rule to the part of expr at position pos.

Examples

Basic Examples

Replace parts 1, 3 and 4 with the rule ce:

In[1]:=
ResourceFunction["ReplacePartWith"][{c, b, c, d}, c -> e, {{1}, {3}, {4}}]
Out[1]=

Properties and Relations

ReplacePartWith takes lists of positions in the same form as generated by Position:

In[2]:=
Position[{a, b, x, c, d, x, e}, x]
Out[2]=
In[3]:=
ResourceFunction[
 "ReplacePartWith"][{a, b, x, c, d, x, e}, {x -> yy}, {{3}, {6}}]
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}]
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}}]
Out[5]=

Possible Issues

Replacing an empty list of positions does not change the expression:

In[6]:=
ResourceFunction["ReplacePartWith"][h[a, b], _ -> x, {}]
Out[6]=

Position {} corresponds to the whole expression:

In[7]:=
ResourceFunction["ReplacePartWith"][h[a, b], _ -> x, {{}}]
Out[7]=

Resource History

License Information