Function Repository Resource:

# GroupCases

Group elements of a list using patterns

Contributed by: Sjoerd Smit
 ResourceFunction["GroupCases"][{e1,e2,…},patt] groups the ei by whether or not they match patt and returns the Association <|patt→{…}, _→{…}|>. ResourceFunction["GroupCases"][{e1,e2,…},patt⧴rhs] applies a transformation to the elements that match patt. ResourceFunction["GroupCases"][list, {spec1,spec2,…}] returns <|spec1→{…},spec2→{…},_→{…}|>. ResourceFunction["GroupCases"][list,<|key1→spec1,key2→spec2,…|>] returns <|key1→{…},key2→{…},_→{…}|>. ResourceFunction["GroupCases"][spec] represents an operator form of ResourceFunction["GroupCases"].

## Details and Options

Every element of the List will be returned exactly once, grouped according to the first pattern that it matches.
Unless explicit keys are given in the input as in ResourceFunction["GroupCases"][list,<|key1spec1,key2spec2,|>], every pattern will be included as a key in the returned Association. If the default pattern _ is not already included in the list of patterns, it will be appended at the end.

## Examples

### Basic Examples (4)

Find all integers and non-integers in a List:

 In[1]:=
 Out[1]=

Apply a transformation to the matching elements:

 In[2]:=
 Out[2]=

Use multiple patterns to split the values by type:

 In[3]:=
 Out[3]=

Transformations can mixed with normal patterns:

 In[4]:=
 Out[4]=

### Scope (2)

Define custom keys for labeling the returned values:

 In[5]:=
 Out[5]=

Replacement rules can also be labeled:

 In[6]:=
 Out[6]=

GroupCases can be defined as an operator:

 In[7]:=
 Out[8]=

### Properties and Relations (2)

GroupCases always matches each element exactly once and all elements are returned under one of the keys in the output:

 In[9]:=
 Out[10]=

If no transformations are used, the following relation will hold:

 In[11]:=
 Out[11]=

All specified patterns will be included as a key in the output Association, even if no value is found for that pattern:

 In[12]:=
 Out[12]=

### Possible Issues (2)

Matching a List at the first level of the input is only possible by specifying a List of patterns to match. The following will match every element in the input because of ambiguity:

 In[13]:=
 Out[13]=

 In[14]:=
 Out[14]=

Sjoerd Smit

## Version History

• 2.0.0 – 20 October 2020
• 1.0.0 – 14 October 2020