Pattern matching in depth
The pattern matching lesson read values apart. This one adds the three forms a real parser and a real protocol need: a pattern that also keeps the whole value, a binary pattern whose size comes from an earlier segment, and a map pattern that reads one key of a message and tolerates the rest. Each one is a Erlang idiom worth recognising.
An as-pattern
A pattern and a name joined by = inside the pattern bind both: the names inside the pattern get the parts, and the name outside gets the whole value. This module classifies a result and returns the value next to the label:
as_pattern.erl
-module(as_pattern). -export([main/0, describe/1]). describe({ok, Number} = Value) when Number > 0 -> {positive, Value}; describe({ok, _Number} = Value) -> {other, Value}; describe(Value) -> {plain, Value}. main() -> io:format("~p~n", [describe({ok, 5})]), io:format("~p~n", [describe({ok, -1})]), io:format("~p~n", [describe(hello)]).
erlc as_pattern.erl
erl -noshell -eval 'as_pattern:main(), halt().'
{positive,{ok,5}} {other,{ok,-1}} {plain,hello}
The as-pattern saves a rebuild of the term and keeps the tag that the field pattern dropped. Without it the first clause would have to write {positive, {ok, Number}} and would lose any extra field the tuple might grow.
A binary pattern with a size
In a binary pattern a segment may use a size that an earlier segment bound. That is the whole trick of a length-prefixed packet: the first byte states how many bytes follow, and the pattern takes exactly that many. A packet that is shorter than its length does not match, so the next clause sees it:
binary_match.erl
-module(binary_match). -export([main/0, parse/1]). parse(<<Size:8, Value:Size/binary, Rest/binary>>) -> {ok, Value, Rest}; parse(_) -> error. main() -> io:format("~p~n", [parse(<<3, "abc", "tail">>)]), io:format("~p~n", [parse(<<9, "abc">>)]).
erlc binary_match.erl
erl -noshell -eval 'binary_match:main(), halt().'
{ok,<<"abc">>,<<"tail">>} error
The size is checked by the match itself: a length of 9 with three bytes left fails before the body runs. The bit syntax lesson names the other specifiers, and Binaries in depth walks a binary segment by segment.
A map pattern with a default
A map pattern names the keys it needs and ignores the rest, which is how a message with an optional field is read. The pattern demands the key with :=; a read with a default uses maps:get/3 in the body. This message handler answers a ping with the sender, or with unknown when the sender is absent:
map_match.erl
-module(map_match). -export([main/0, handle/1]). handle(#{type := ping} = Message) -> {ping, maps:get(from, Message, unknown)}; handle(Message) -> {other, maps:get(type, Message, none)}. main() -> io:format("~p~n", [handle(#{type => ping, from => ada})]), io:format("~p~n", [handle(#{type => stop})]).
erlc map_match.erl
erl -noshell -eval 'map_match:main(), halt().'
{ping,ada} {other,stop}
The first clause matches a map with a type key and binds the whole map, so the body can read an optional key with its default. The second clause has no type in its pattern and reads it with a default as well, which is why an unrelated map still gets an answer instead of a crash.
List and tuple patterns
A list pattern always ends in a list: [First, Second | Rest] names two items and keeps the rest, and [] is the empty list. A tuple pattern has one segment per position, so the arity is part of the match. The two compose:
erl
1> [{ok, A}, {ok, B} | Rest] = [{ok, 1}, {ok, 2}, {ok, 3}]. [{ok,1},{ok,2},{ok,3}] 2> {A, B, Rest}. {1,2,[{ok,3}]} 3> [1, 2 | 3]. [1,2|3]
The third line builds an improper list: the tail is the number 3, not a list. It matches the pattern [1, 2 | Tail] with Tail = 3, but length/1 refuses it. A proper list ends in [], and the lists lesson explains why that matters.
Which side of the match
An as-pattern works in either order, but the house style puts the pattern on the left
and the whole value on the right: {ok, Number} = Value, not
Value = {ok, Number}. The two bind the same names, and the style
checker of the course flags the second form in a function parameter because a reader
expects the shape first and the name second.
The rule costs nothing and makes a head read like a type: the pattern says what the
argument looks like, and the name at the end is the whole argument for the body. The
records lesson uses the same order for a
record, and the guards lesson adds the
condition after it.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does an as-pattern
{ok, N} = Valuebind?Answer
Both
NandValue, withValueholding the whole termThe pattern binds
Nto the part andValueto the whole matched term. -
In
<<Size:8, Value:Size/binary>>, where does the size come from?Answer
The earlier segment of the same pattern
The first segment binds
Size, and the second takes that many bytes. -
What happens when a packet is shorter than its length field?
Answer
The pattern does not match
The pattern demands the bytes it declared, so a short packet falls to the next clause.
-
Which arrow demands a key in a map pattern?
Answer
:=:=matches a key that must exist;=>is rejected in a pattern. -
What does this module print?
-module(q4). -export([main/0]). main() -> Message = #{type => ping, from => ada}, Result = case Message of #{type := ping} = Whole -> {ping, maps:get(from, Whole, unknown)}; _ -> other end, io:format("~p~n", [Result]).Answer
{ping,ada}The map pattern matches the
typekey, and the body reads the optionalfromkey. -
What is
[1, 2 | 3]?Answer
An improper list whose tail is the number 3
The tail of a cons must be a list, and here it is a number, so the list is improper.
-
Which order does the course use for an as-pattern in a function head?
Answer
{ok, N} = ValueThe shape comes first and the name for the whole value comes last, so the head reads like a type.
-
What does this module print?
-module(q1). -export([main/0]). main() -> {ok, Number} = Value = {ok, 7}, io:format("~p~n", [{Number, Value}]).Answer
{7,{ok,7}}The pattern binds
Numberto 7 andValueto the whole tuple. -
What does this module print?
-module(q2). -export([main/0]). parse(<<Size:8, Value:Size/binary, Rest/binary>>) -> {ok, Value, Rest}; parse(_) -> error. main() -> io:format("~p~n", [parse(<<2, "ab", "cd">>)]).Answer
{ok,<<"ab">>,<<"cd">>}The size 2 takes two bytes for the value, and the rest segment keeps the last two.
-
What does this module print?
-module(q3). -export([main/0]). main() -> [First, Second | Rest] = [1, 2, 3, 4], io:format("~p~n", [{First, Second, Rest}]).Answer
{1,2,[3,4]}The first two names take the first two items and
Restkeeps the remaining list.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev