This EEP allows the key of a map association in a pattern to use variables that are bound by other parts of the same pattern, such as another argument of the same function head:
local_number(Number, #{numbers := #{Number := Metadata}}) ->
{Number, Metadata};
local_number(_, _) ->
not_local.
The parts of the pattern can be written in any order, as long as the keys do not depend on each other in a cycle. This is what EEP 43 described when maps were introduced, but it was never implemented. Programs that are valid today keep their meaning and their generated code.
A common need is to use a value from one argument to select an entry
in a map from another argument. A typical case is a request and the
state in a gen_server callback:
handle_call({get, Id}, _From, #{sessions := #{Id := Session}} = S) ->
{reply, {ok, Session}, S};
handle_call({get, _}, _From, S) ->
{reply, {error, not_found}, S}.
handle_info({'DOWN', Ref, process, _, _}, #{monitors := #{Ref := Id}} = S) ->
{noreply, remove(Id, S)};
handle_info({'DOWN', _, process, _, _}, S) ->
{noreply, S}.
Today such clauses must be written in two steps:
case loses the fall-through to the next clause, so the
fallback code is duplicated or moved to a helper function.is_map_key/2 and map_get/2 only works when the
value does not have to be matched against a pattern.The following is from the data plan of the Kazoo telephony platform. A connection name is taken from one map and used as a key into another map, in two steps:
attachment_handler(#{<<"handler">> := Handler}) -> Handler;
attachment_handler(_Attachments) -> undefined.
add_attachment_proxy(Plan, RootAttachments, ClassAttachments, Conn) ->
#{Conn := #{<<"handler">> := HandlerBin,
<<"settings">> := Settings}} = RootAttachments,
...
The second step fails with badmatch if the connection is missing.
With this EEP it becomes one function, with a clause for the missing
connection:
add_attachment_proxy(Plan, #{<<"handler">> := Conn} = ClassAttachments,
#{Conn := #{<<"handler">> := HandlerBin,
<<"settings">> := Settings}}) ->
...;
add_attachment_proxy(Plan, _ClassAttachments, _RootAttachments) ->
Plan.
With more clauses, the code that must be written by hand grows. The following three clauses:
lookup({get, Id}, #{sessions := #{Id := S}}) -> {ok, S};
lookup({get, Id}, #{pending := #{Id := P}}) -> {pending, P};
lookup(_, _) -> not_found.
need two functions and a fallback in two places to get the same semantics today:
lookup({get, Id} = Req, #{sessions := Sessions} = State) ->
case Sessions of
#{Id := S} -> {ok, S};
_ -> lookup_pending(Req, State)
end;
lookup(Req, State) ->
lookup_pending(Req, State).
lookup_pending({get, Id}, #{pending := Pending}) ->
case Pending of
#{Id := P} -> {pending, P};
_ -> not_found
end;
lookup_pending(_, _) ->
not_found.
The best-known example is count_characters/2 from the second edition
of Programming Erlang, which has never compiled:
count_characters(Str) -> count_characters(Str, #{}).
count_characters([H|T], #{ H := N }=X) -> count_characters(T, X#{ H := N+1 });
count_characters([H|T], X) -> count_characters(T, X#{ H => 1 });
count_characters([], X) -> X.
With this EEP it compiles. So does the version with the arguments
swapped, count_characters(#{ H := N }=X, [H|T]), which
#4963 notes would also have to work.
Users have asked for this since maps were introduced, for example on erlang-questions in 2016 and in GitHub issues #3056, #3467, #4963 and #5796.
Today, all variables in the key K of an association K := V in a
map pattern must be bound before the pattern. This EEP relaxes that
rule. A variable in a map key in a pattern must be either:
The pattern is the whole unit that is matched at once:
case, receive, or try ... catch clause,Pattern = Expr,maybe match expression Pattern ?= Expr,An association whose key uses variables of the second kind is matched after the parts of the pattern that bind those variables. The order in which the parts are written does not matter:
f(K, #{K := V}) -> V. % Before the map.
g(#{K := V}, K) -> V. % After the map.
h(#{a := K, K := V}) -> V. % In the same map.
i(#{K := V, a := K}) -> V. % Same, other order.
j({A, #{A := B}, #{B := C}}) -> C. % A chain.
The examples in the section “Pattern matching: Continued” of EEP 43 are valid:
#{ K := V, id := K } = M = #{ id => b, a => 1, b => 2, c => 3},
{ #{ X := Y }, X } = { #{ 5 => 10 }, 5 },
The keys must not depend on each other in a cycle. The variables that can be used in keys are computed as follows:
A key variable that is not added is an error. The compiler reports it as unbound, with the same message as today:
f(#{K := K}) -> K. % variable 'K' is unbound
g({#{A := B}, #{B := A}}) -> {A, B}. % 'A' and 'B' are unbound
A variable that occurs more than once must match the same term everywhere, as today. It can be used in a key as soon as any one of its occurrences has been matched. The following clause matches a map that associates the second argument with itself:
h(#{K := K}, K) -> K.
In a fun head or a generator pattern, a variable shadows any variable with the same name bound before it. If a variable in a key is also bound before the fun or the generator, the key refers to the variable bound before, as today:
K = a,
F = fun(K, #{K := V}) -> {K, V} end,
{b, 1} = F(b, #{a => 1, b => 2}).
The compiler warns about the shadowing, as it does today.
The generators of a zip (G1 && G2) are matched one at a time, from
left to right. A key in the pattern of a generator can therefore use
variables bound in the same generator or in a generator to its left,
but not in a generator to its right:
[Y || {K, _} <- L1 && #{K := Y} <- L2] % valid
[Y || #{K := Y} <- L2 && {K, _} <- L1] % variable 'K' is unbound
If a postponed association does not match, the whole pattern does not
match. That happens when the value is not a map, when the key is
missing, when the value does not match, or when the key expression
fails. The next clause is tried, and a match expression fails with
{badmatch, Value} for the original value. Guards can use all the
variables of the pattern.
f(Sz, <<X:Sz>>) is still illegal.P1 = P2 = Expr in a body, are still
evaluated from right to left.EEP 43 described keys bound by other parts of a pattern, with a
reordering that “extends to all terms in a matching expression”, and
included examples such as freq([I|Is], #{I := C} = M). Erlang/OTP 17
released maps without variable keys in patterns, OTP 18 allowed keys
bound before the pattern, and OTP 23 (EEP 52) allowed key
expressions, still bound before the pattern.
In 2020, Björn Gustavsson made a prototype that reordered the arguments and elements of a pattern by a topological sort of their dependencies. It was shelved because repeated variables created false cycles, and because the error messages became confusing.
The patterns of a function head have no defined matching order, and maps are unordered. EEP 43 specified a dependency order, and #4963 noted that a solution would have to work with the arguments swapped. A left-to-right rule would also conflict with the compound pattern operator, whose operands are matched with no defined order (PR #6415).
In foo(#{K := K}, K) the variable K both defines and uses the
association K := K, which looks like a cycle if dependencies are
computed between positions. This EEP computes them on variables
instead: a variable can be used in a key as soon as any of its
occurrences has been matched (step 1 of the specification). The
compiler then binds each variable at the occurrence that is matched
first. The other occurrences become the same equality tests that the
compiler generates for repeated variables today. foo(#{K := K}, K)
therefore means that the map associates the second argument with
itself, which is the meaning suggested in #4963.
A key variable that can never be bound is reported as unbound, as today, so programs that stay invalid get the same messages. A dedicated message for circular keys could be added later.
Letting a key refer to the variable bound before the fun keeps the meaning of existing code, which compiles today with a shadowing warning.
Binary patterns are matched sequentially, and sizes bound in earlier segments already work. Sizes bound in other parts of the pattern could use the same mechanism, but they are left out to keep this EEP small.
#{k := K} = #{K := V} is valid as a pattern, but the compiler warns
that a compound pattern with constructors on both sides may become an
error in a future release. The unified form #{k := K, K := V} means
the same and does not get the warning.
is_map_key/2 and map_get/2 cannot match
the value against a pattern, nor handle nested maps.^K is not needed, because a
variable that occurs twice in an Erlang pattern is already the same
variable.Only clauses that use the feature are affected. The compiler splits
such a clause into nested case expressions, using the same mechanism
(letrec_goto) as for the key and size expressions of EEP 52. The
remaining clauses are matched in a continuation, which can test parts
of the arguments again. The code generated for all other clauses is
unchanged.
For the simple shape, the generated code is the same as the code for
the two-step version. Both of the following compile to the same BEAM
instructions (is_map, get_map_elements, is_map,
get_map_elements):
local_number(Number, #{numbers := #{Number := Metadata}}) -> ...
local_number(Number, #{numbers := Numbers}) ->
case Numbers of
#{Number := Metadata} -> ...;
#{} -> not_local
end;
In a benchmark with 8 to 3 000 000 numbers in the map, both versions took the same time at every size. The new version was at most a few nanoseconds faster or slower, and the sign of the difference changed between runs.
Programs that compiled before keep their meaning and their generated code. Only patterns that were rejected before are now accepted. Two of them are documented as errors today:
illegal_example6(Key, #{Key := Value}) -> Value. in EEP 52;fun(#{Key := Value} = #{key := Key}) -> Value end in the section
on the compound pattern operator in the Reference Manual.Core Erlang does not change, because the compiler lowers the new patterns to ordinary Core Erlang before any other pass sees them. Tools that work on Core Erlang, such as Dialyzer, are not affected.
Tools that check variables in the abstract format must accept the new
patterns. In Erlang/OTP that is erl_lint, erl_eval and the
debugger.
Parse transforms that run before erl_lint see the same abstract
format as before. For example, ets:fun2ms/1 already translates
fun({K, #{K := V}}) -> V end to a match specification with a
variable map key, which ETS rejects. This EEP does not change that.
A reference implementation is available, based on the master branch of Erlang/OTP (30.0-rc0):
erl_lint collects the key variables that are not bound before the
pattern, and resolves them when the whole pattern is known
(map_key_uses/5, map_key_avail/2).v3_core:
pat_binding_occurrences/2);split_dep_keys/2), reusing the
mechanism of EEP 52.erl_eval and dbg_ieval match the postponed associations once the
variables in their keys are bound.map_SUITE (compiler and debugger),
erl_lint_SUITE, erl_eval_SUITE and error_SUITE.With these changes, the whole compiler test suite passes, except 13
test cases that were skipped because PropEr was not installed. So do
the erl_lint, erl_eval, shell, qlc, ms_transform and
erl_expand_records suites of STDLIB and the debugger test suite.
About 2900 randomly generated patterns gave the same results compiled,
in erl_eval and in the debugger.
One known issue is shared with the key and size expressions of
EEP 52. When the compiler can prove that a split clause never
matches, for example because the case argument is a literal, it can
warn that “no clause will ever match”, even when later clauses match.
This document is placed in the public domain or under the CC0-1.0-Universal license, whichever is more permissive.