Function Repository Resource:

HighlightCases

Source Notebook

Visualize cases of matched patterns in any expression

Contributed by: Michael Sollami

ResourceFunction["HighlightCases"][expr,pattern]

displays expr with matching cases highlighted.

ResourceFunction["HighlightCases"][expr,pattern,levelspec]

displays expr with matching cases highlighted on levels specified by levelspec.

Details and Options

Like Cases, ResourceFunction["HighlightCases"] takes the option Heads (True by default) which specifies whether to match within expression heads.
Also like Cases, the second argument can include Rule and RuleDelayed expressions. The right-hand side of a rule indicates the styling used to highlight the corresponding matches.
When specifing multiple patterns, use a List to style matches with different colors and use Alternatives for the same color.

Examples

Basic Examples (5) 

Highlight cases in a List:

In[1]:=
ResourceFunction["HighlightCases"][Alphabet[], "a" | "e" | "i" | "o" | "u"]
Out[1]=

Use a list of patterns to style matching cases with multiple colors:

In[2]:=
ResourceFunction["HighlightCases"][
 Range[20], {1, 4, 7, 11 | 12, 17}]
Out[2]=

Highlight all the primes:

In[3]:=
Multicolumn[
 ResourceFunction["HighlightCases"][Range[49], n_Integer?PrimeQ -> LightBlue]]
Out[3]=

Use delayed rules for custom highlight styles:

In[4]:=
ResourceFunction["HighlightCases"][Range[7], n_Integer :> Hue[n/7]]
Out[4]=

Highlight heads in held expressions:

In[5]:=
ResourceFunction["HighlightCases"][
 HoldForm[\[Pi] + E*I + 1*(2 + 3)], {Plus, Times}, {3, 4}]
Out[5]=

Scope (4) 

Highlight matching cases on specific levels:

In[6]:=
ResourceFunction["HighlightCases"][{1, 1, {1, {1}, 1}}, 1, {2}]
Out[6]=

Use multiple highlight styles with overlapping patterns:

In[7]:=
ResourceFunction[
 "HighlightCases"][{{1, 2}, {3, 4}}, {_Integer -> Green, {_, _} -> Blue}]
Out[7]=

Restrict HighlightCases to match only on levels 0 to 1:

In[8]:=
ResourceFunction[
 "HighlightCases"][{1, {2, {3}}}, _List -> Automatic, {0, 1}]
Out[8]=

Restrict HighlightCases to match only on level 2:

In[9]:=
 ResourceFunction["HighlightCases"][
 Range[25], {_?(Mod[#, 3] == 0 &), _?(Mod[#, 5] == 0 &)}]
Out[9]=

Possible Issues (2) 

Using a list of patterns in the second argument of HighlightCases will match each of the elements in the list:

In[10]:=
ResourceFunction["HighlightCases"][{{1, 2, 3}, {3, 4, 5}}, {1, 2, 3}]
Out[10]=

Use HoldPattern to treat the list as a single pattern:

In[11]:=
ResourceFunction["HighlightCases"][{{1, 2, 3}, {3, 4, 5}}, HoldPattern[{1, 2, 3}]]
Out[11]=

Publisher

Michael Sollami

Version History

  • 1.0.0 – 23 April 2020

Related Resources

License Information