Function Repository Resource:

PositionCases

Source Notebook

Cases for matching subexpressions together with their positions

Contributed by: Nikolay Murzin

ResourceFunction["PositionCases"][expr,pattern]

gives a list of all parts of expr that match the pattern.

ResourceFunction["PositionCases"][expr,patternrhs]

gives the values of rhs that match the pattern.

Details

PositionPattern is a special head for matching subexpressions together with their positions.

Examples

Basic Examples (3) 

Find all cases matching a position pattern:

In[1]:=
ResourceFunction["PositionCases"][f[a, g[b, h[c, d]]], PositionPattern[{___, 0}, _]]
Out[1]=

Find all cases matching both position and an ordinary pattern:

In[2]:=
ResourceFunction["PositionCases"][f[a, g[b, h[c, d]]], PositionPattern[{__}, _[_, _]]]
Out[2]=

Use a rule to compute arbitrary combinations of subexpressions and their positions:

In[3]:=
ResourceFunction["PositionCases"][f[a, g[b, g[c, d]]], g[PositionPattern[p_, e_], _] :> p -> e]
Out[3]=

Scope (5) 

Find all positions deeper than specified depth:

In[4]:=
ResourceFunction["PositionCases"][f[a, g[b, h[c, d]]], PositionPattern[pos_, x_] /; Length[pos] > 2 :> pos -> x]
Out[4]=

Find all sub heads:

In[5]:=
ResourceFunction["PositionCases"][f[a, g[b, h[c, d]]], PositionPattern[{p : ___, 0}, x_] :> {p} -> x]
Out[5]=

Use found positions for manipulation of an underlying expression:

In[6]:=
ResourceFunction["PositionCases"][expr = f[a, g[b, g[c, d]]], g[PositionPattern[p_, _], _] :> ReplacePart[expr, p -> \[Bullet]]]
Out[6]=

Use PatternTest:

In[7]:=
ResourceFunction["PositionCases"][expr = f[a, g[1, g[c, d]]], PositionPattern[p : {_?(GreaterThan[1]) ..}, x_] :> p -> x]
Out[7]=

Return raw PositionPattern expressions:

In[8]:=
ResourceFunction["PositionCases"][expr = f[a, g[1, g[c, d]]], pp : PositionPattern[_, _Symbol] :> pp]
Out[8]=

Properties and Relations (1) 

Without PositionPattern, PositionCases works like Cases[expr,patt,All]:

In[9]:=
ResourceFunction["PositionCases"][f[a, g[b, g[c, d]]], g[_, _]]
Out[9]=
In[10]:=
Cases[f[a, g[b, g[c, d]]], g[_, _], All]
Out[10]=

Publisher

N. Murzin

Version History

  • 1.0.0 – 01 March 2021

Related Resources

License Information