Function Repository Resource:

BeheadAt

Source Notebook

Remove heads from subexpressions

Contributed by: Nikolay Murzin

ResourceFunction["BeheadAt"][expr,pos]

returns a beheaded expr at pos.

ResourceFunction["BeheadAt"][expr,pos,def]

replaces subexpressions without parts with def.

ResourceFunction["BeheadAt"][pos]

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

Examples

Basic Examples (2) 

Behead the expression at a given position:

In[1]:=
ResourceFunction["BeheadAt"][{x, head1[y, z], head2[a, b]}, {2}]
Out[1]=

Behead at multiple positions:

In[2]:=
ResourceFunction[
 "BeheadAt"][{x, head1[y, z], head2[a, b]}, {{2}, {3}}]
Out[2]=

Scope (7) 

Behead at subhead position to return Sequence[]:

In[3]:=
ResourceFunction["BeheadAt"][f, {{}}]
Out[3]=
In[4]:=
ResourceFunction["BeheadAt"][f[x], {0}]
Out[4]=
In[5]:=
ResourceFunction["BeheadAt"][{f[x], y}, {{1, 0}, {2}}]
Out[5]=

Provide a different expression instead of Sequence[]:

In[6]:=
ResourceFunction["BeheadAt"][{x, f[y], f[z]}, {{1}, {2, 0}, {3}}, XXX]
Out[6]=

Beheading at subhead position results in Sequence[…]:

In[7]:=
ResourceFunction["BeheadAt"][f[x, y][z], {0}]
Out[7]=

Use integer positions:

In[8]:=
ResourceFunction["BeheadAt"][{head[x, y]}, 1]
Out[8]=

Use Unevaluated to prevent premature evaluation:

In[9]:=
ResourceFunction["BeheadAt"][Unevaluated@{Print[x, y]}, 1]
Out[9]=

Use operator form:

In[10]:=
ResourceFunction["BeheadAt"][{{}}] /@ {x, f[y], g[a, b]}
Out[10]=

BeheadAt also works inside held arguments:

In[11]:=
ResourceFunction["BeheadAt"][x_ :> head[x + 1 + 1], {2}]
Out[11]=

Properties and Relations (3) 

In most cases, BeheadAt is equivalent to using Delete and FlattenAt or ReplacePart with Sequence:

In[12]:=
Delete[Hold[head[1, 2]], {1, 0}]
Out[12]=
In[13]:=
FlattenAt[Hold[head[1, 2]], {1}]
Out[13]=
In[14]:=
ReplacePart[Hold[head[1, 2]], {1, 0} -> Sequence]
Out[14]=
In[15]:=
ResourceFunction["BeheadAt"][Hold[head[1, 2]], {1}]
Out[15]=

ReplacePart will not work deeper than the first level inside held arguments:

In[16]:=
ReplacePart[Hold[f[head[1, 2]]], {1, 1, 0} -> Sequence]
Out[16]=
In[17]:=
ResourceFunction["BeheadAt"][Hold[f[head[1, 2]]], {1, 1}]
Out[17]=

Delete and FlattenAt replace subheads with Sequence instead of beheading:

In[18]:=
Delete[f[x], {0}]
Out[18]=
In[19]:=
FlattenAt[f[x], {{}}]
Out[19]=

This is equivalent to BeheadAt with Sequence:

In[20]:=
ResourceFunction["BeheadAt"][f[x], {0}, Sequence]
Out[20]=

Possible Issues (1) 

Trying to behead a nonexistent subexpression generates a message but still evaluates:

In[21]:=
ResourceFunction["BeheadAt"][{f[x], y}, {{1}, {2}, {3}, {10}}]
Out[21]=

Version History

  • 1.0.0 – 05 April 2022

Related Resources

Author Notes

My main motivation was to remove heads inside held arguments.
Delete and FlattenAt achieve the same end result, but BeheadAt still has a few useful differences.

License Information