Function Repository Resource:

PatternSort

Source Notebook

Sort a list of patterns according to their precedence

Contributed by: Taliesin Beynon (Wolfram Research)

ResourceFunction["PatternSort"][{patt1,patt2,}]

returns the patti in order of most specific to least specific.

Details and Options

The head of the patti need not be List.

Examples

Basic Examples (5) 

Sort patterns for one argument or a sequence of arguments:

In[1]:=
ResourceFunction["PatternSort"][{x___, x_, x__, _}]
Out[1]=

For definite types of arguments:

In[2]:=
ResourceFunction[
 "PatternSort"][{x_Integer, x_Real, x_, x_Integer | x_Real, x_String}]
Out[2]=

Arguments with a head f:

In[3]:=
ResourceFunction["PatternSort"][{f[x_], f[_], f[x___], f[x_, ___]}]
Out[3]=

Sequences of arguments:

In[4]:=
ResourceFunction[
 "PatternSort"][{{x__, PatternSequence[a, c, b], y__}, {x_, PatternSequence[a, c, b], y___}}]
Out[4]=

For ambiguous matches:

In[5]:=
ResourceFunction[
 "PatternSort"][{{Shortest[x__], y__}, {x__, Shortest[y__]}}]
Out[5]=

Properties and Relations (2) 

The patterns do not need to be in a List:

In[6]:=
ResourceFunction["PatternSort"][g[f[___], f[_], f[__]]]
Out[6]=

Repeated names add specificity:

In[7]:=
ResourceFunction["PatternSort"][{f[x_, _], f[x_, x_]}]
Out[7]=

Publisher

Enrique Zeleny

Version History

  • 1.0.0 – 22 June 2020

Related Resources

License Information