Function Repository Resource:

SpliceAt

Source Notebook

Splice expressions at certain positions

Contributed by: Nikolay Murzin

ResourceFunction["SpliceAt"][expr,{e1,e2,},pos]

splices expressions ei at position pos of expr.

ResourceFunction["SpliceAt"][expr,{p1{e11,e12,},p2{e21,e22,},}]

splices expressions eij at corresponding positions pi.

ResourceFunction["SpliceAt"][{e1,e2,}, pos]

represents an operator form that can be applied to an expression.

ResourceFunction["SpliceAt"][{p1{e11,e12,},p2{e21,e22,},}]

represents an operator form with rules.

Examples

Basic Examples (3) 

Splice a list of expressions inside another expression:

In[1]:=
ResourceFunction["SpliceAt"][f[x, y], {a, b}, {2}]
Out[1]=

Splice at multiple positions:

In[2]:=
ResourceFunction["SpliceAt"][f[x, y], {a, b}, {{1}, {3}}]
Out[2]=

Splice with rules:

In[3]:=
ResourceFunction["SpliceAt"][f[x, y], {{1} -> {a, b}, {3} -> {c, d}}]
Out[3]=

Scope (3) 

Use Unevaluated to prevent premature evaluation:

In[4]:=
ResourceFunction["SpliceAt"][Hold@f[x, y], Unevaluated@{Print[1], b}, {1, 2}]
Out[4]=

Use RuleDelayed to delay evaluation for rules:

In[5]:=
ResourceFunction["SpliceAt"][
 Hold@f[x, y], {1, 2} :> {Print[1], 2 + 2, 1 + 1}]
Out[5]=

Use operator forms:

In[6]:=
ResourceFunction["SpliceAt"][{a, b}, {{2}}] /@ {f[x], g[y]}
Out[6]=
In[7]:=
ResourceFunction["SpliceAt"][{2} :> {a, b}] /@ {f[x], g[y]}
Out[7]=

Properties and Relations (4) 

In most cases, SpliceAt is just equivalent to Insert with Sequence:

In[8]:=
Insert[Hold[a, b], Unevaluated@Sequence[x, y], {2}]
Out[8]=
In[9]:=
ResourceFunction["SpliceAt"][Hold[a, b], {x, y}, {2}]
Out[9]=

But Insert will not work at deeper than first level inside held arguments:

In[10]:=
Insert[Hold[{a, b}], Unevaluated@Sequence[x, y], {1, 2}]
Out[10]=

While SpliceAt works as expected:

In[11]:=
ResourceFunction["SpliceAt"][Hold[{a, b}], {x, y}, {1, 2}]
Out[11]=

Also Insert does not support multiple insertions, while SpliceAt does:

In[12]:=
ResourceFunction["SpliceAt"][
 Hold[{a, b}], {{1, 1} -> {x, y}, {1, 3} -> {xx, yy}}]
Out[12]=

Possible Issues (2) 

Root position is invalid:

In[13]:=
ResourceFunction["SpliceAt"][f[x], {a, b}, {{}}]
Out[13]=

Subhead position is invalid:

In[14]:=
ResourceFunction["SpliceAt"][f[x], {a, b}, {0}]
Out[14]=

Version History

  • 1.0.0 – 19 April 2022

Related Resources

Author Notes

Main motivation was to splice inside held arguments

License Information