Skip to content
AgileLogics
7 min read

Patterns

Prerequisites: Functional programming

A pattern describes a shape of expression. Patterns are used in function definitions, Cases, Switch, rules, and more.

The basic blanks

Pattern Matches
_ any single expression
_h any expression with head h (_Integer, _String, _List)
__ a sequence of one or more expressions
___ a sequence of zero or more expressions
x_ any expression, named x
MatchQ[3, _Integer]
MatchQ[3.0, _Integer]
MatchQ[{1, 2}, {_, _}]
MatchQ[f[1, 2, 3], f[__]]
MatchQ[f[], f[__]]
MatchQ[f[], f[___]]
True
False
True
True
False
True

Cases: pick out matching parts

mixed = {1, "a", 2.5, 3, "b"};
Cases[mixed, _Integer]
Cases[mixed, _String]
Cases[mixed, _Integer | _Real]
Cases[{f[1], g[2], f[3]}, f[n_] -> n]
DeleteCases[{1, 0, 2, 0}, 0]
{1, 3}
{a, b}
{1, 2.5, 3}
{1, 3}
{1, 2}
  • | means "or" in a pattern.
  • Cases[list, pattern -> result] transforms each match.

Conditions

Cases[Range[10], n_ /; n > 7]
Cases[Range[10], _?PrimeQ]
Count[{1, 2, 3, 4}, _?EvenQ]
{8, 9, 10}
{2, 3, 5, 7}
2
  • pattern /; condition — the match only counts if the condition is true.
  • _?test — the expression must pass the function test.

Patterns in definitions

A function can have one definition per shape of input — a clean way to handle different cases:

area[circle[r_]] := Pi r^2
area[rect[w_, h_]] := w h
area /@ {circle[1], rect[2, 3], circle[2]}

total[list : {__Integer}] := Total[list]
total[{1, 2, 3}]
total[{1, a}]
{Pi, 6, 4 Pi}
6
total[{1, a}]
  • circle and rect don't need to be defined — they're just labels, a lightweight way to make data structures.
  • name : pattern names a whole pattern: list is the entire list of integers.

Common mistakes

  • f[x_Real] doesn't match 3 — an integer isn't a Real. Use x_?NumericQ to accept any number.
  • Putting a condition that uses an unnamed part: in _ /; # > 0, # means nothing. Name it: x_ /; x > 0.