8.4 Patterns
8.4 Patterns
A pattern has the same structure as a term but can contain unbound variables.
Example:
Name1
[H|T]
{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:
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:
f({connect,From,To,Number,Options}, To) ->
Signal = {connect,From,To,Number,Options},
...;
f(Signal, To) ->
ignore.
can instead be written as
f({connect,_,To,_,_} = Signal, To) ->
...;
f(Signal, To) ->
ignore.
String Prefix in Patterns
When matching strings, the following is a valid pattern:
f("prefix" ++ Str) -> ...
This is syntactic sugar for the equivalent, but harder to read:
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:
case {Value, Result} of
{?THRESHOLD+1, ok} -> ...
