Function Repository Resource:

PatternBindings

Source Notebook

Pick named elements of a pattern

Contributed by: Robby Villegas and Wolfram Staff

ResourceFunction["PatternBindings"][expr,pattern]

gives a list of elements of expr matching named parts of pattern.

Details and Options

For the named parts ni and matching elements ei, ResourceFunction["PatternBindings"][] returns a list in the form {HoldPattern[n1]e1,HoldPattern[n2]e2,}.
If expr does not match pattern, ResourceFunction["PatternBindings"][] returns a Failure[] object.

Examples

Basic Examples (2) 

Find parts of an expression that match the named elements of a pattern:

In[1]:=
ResourceFunction["PatternBindings"][x^2, u_^a_]
Out[1]=

Test if an expression matches the pattern:

In[2]:=
ResourceFunction["PatternBindings"][x + y + z, _ + _]
Out[2]=

Applications (1) 

PatternBindings can be useful for debugging and code analysis:

In[3]:=
SetAttributes[f, OneIdentity]
In[4]:=
ResourceFunction["PatternBindings"][a, f[x_ : 0, y_]]
Out[4]=

Properties and Relations (4) 

PatternBindings returns a failure object in cases for which MatchQ returns False:

In[5]:=
ResourceFunction["PatternBindings"][x ^2, u_^3]
Out[5]=
In[6]:=
MatchQ[x ^2, u_^3]
Out[6]=

PatternBindings uses the standard rules when resolving ambiguity:

In[7]:=
ResourceFunction["PatternBindings"][{x, y}, {u___, v___}]
Out[7]=

Compare, for instance, with pattern matching in a function definition:

In[8]:=
func[u___, v___] := {"u"[u], "v"[v]}
In[9]:=
func[x, y]
Out[9]=

PatternBindings picks up only named elements in patterns:

In[10]:=
ResourceFunction["PatternBindings"][{x, y}, {u_, _}]
Out[10]=

ReplaceAll can be used instead of PatternBindings:

In[11]:=
{a, b, c, d, e, f, g} /. {x__, Longest[y__], z__} -> {{x}, {y}, {z}}
Out[11]=
In[12]:=
ResourceFunction[
 "PatternBindings"][{a, b, c, d, e, f, g}, {x__, Longest[y__], z__}]
Out[12]=

Possible Issues (1) 

PatternBindings does not find elements taken verbatim:

In[13]:=
ResourceFunction["PatternBindings"][x_, Verbatim[x_]]
Out[13]=

Version History

  • 1.0.0 – 17 January 2020

Related Resources

License Information