Function Repository Resource:

ToExplicitPosition

Source Notebook

Turn a general position specification, such as a span, into a list of explicit positions

Contributed by: Nikolay Murzin

ResourceFunction["ToExplicitPosition"][expr, pos]

returns a list of explicit positions of expr corresponding to the specification pos.

Details

Explicit positions are lists of non-negative integers

Examples

Basic Examples (4) 

Return an explicit list of positions given an expression and All as position specification:

In[1]:=
ResourceFunction["ToExplicitPosition"][f[{1}, {2, 3}, {4, 5, 6}], All]
Out[1]=

Use a negative integer to return the explicit position of the last part of the top level:

In[2]:=
ResourceFunction["ToExplicitPosition"][f[{1}, {2, 3}, {4, 5, 6}], -1]
Out[2]=

Use ;; (Span):

In[3]:=
ResourceFunction["ToExplicitPosition"][
 f[{1}, {2, 3}, {4, 5, 6}], ;; 2]
Out[3]=

Use UpTo:

In[4]:=
ResourceFunction["ToExplicitPosition"][f[{1}, {2, 3}, {4, 5, 6}], 2 ;; UpTo[4]]
Out[4]=

Scope (4) 

Show deeper positions:

In[5]:=
ResourceFunction["ToExplicitPosition"][
 f[{1}, {2, 3}, {4, 5, 6}], {;; 2, All}]
Out[5]=

Show a list of positions:

In[6]:=
ResourceFunction["ToExplicitPosition"][
 f[{1}, {2, 3}, {4, 5, 6}], {{All}, {All ;; ;; -1}}]
Out[6]=

Inside of heads:

In[7]:=
ResourceFunction["ToExplicitPosition"][
 f[{1}, {2, 3}, {4, 5, 6}][a, b], {0, All, All}]
Out[7]=

Use Unevaluated to prevent evaluation:

In[8]:=
ResourceFunction["ToExplicitPosition"][
 Unevaluated[{1 + 2, Print[3]}], {All, All}]
Out[8]=

Properties and Relations (1) 

Position with a level specification is the same up to reordering as ToExplicitPosition with appropriate combinations of All:

In[9]:=
Position[f[{1}, {2, 3}, {4, 5, 6}], _, 2, Heads -> False] // Sort
Out[9]=
In[10]:=
ResourceFunction["ToExplicitPosition"][
  f[{1}, {2, 3}, {4, 5, 6}], {{All}, {All, All}}] // Sort
Out[10]=

Possible Issues (1) 

Integers inside Span only return valid positions compatible with the span specification:

In[11]:=
ResourceFunction["ToExplicitPosition"][
 f[{1}, {2, 3}, {4, 5, 6}], {All, ;; 3}]
Out[11]=
In[12]:=
ResourceFunction["ToExplicitPosition"][
 f[{1}, {2, 3}, {4, 5, 6}], {All, ;; UpTo[3]}]
Out[12]=

Version History

  • 1.0.0 – 10 May 2022

Related Resources

License Information