8.4 Patterns

A pattern has the same structure as a term but can contain unbound variables.

Example:

  1. Name1
  2. [H|T]
  3. {error,Reason}

Patterns are allowed in clause heads, case and receive expressions, and match expressions.

Match Operator = in Patterns

If Pattern1 and Pattern2 are valid patterns, the following is also a valid pattern:

  1. Pattern1 = Pattern2

When matched against a term, both Pattern1 and Pattern2 are matched against the term. The idea behind this feature is to avoid reconstruction of terms.

Example:

  1. f({connect,From,To,Number,Options}, To) ->
  2. Signal = {connect,From,To,Number,Options},
  3. ...;
  4. f(Signal, To) ->
  5. ignore.

can instead be written as

  1. f({connect,_,To,_,_} = Signal, To) ->
  2. ...;
  3. f(Signal, To) ->
  4. ignore.

String Prefix in Patterns

When matching strings, the following is a valid pattern:

  1. f("prefix" ++ Str) -> ...

This is syntactic sugar for the equivalent, but harder to read:

  1. f([$p,$r,$e,$f,$i,$x | Str]) -> ...

Expressions in Patterns

An arithmetic expression can be used within a pattern if it meets both of the following two conditions:

  • It uses only numeric or bitwise operators.
  • Its value can be evaluated to a constant when complied.Example:
  1. case {Value, Result} of
  2. {?THRESHOLD+1, ok} -> ...