Skip to main content

W0032 - maps:find/2 usage rather than dedicated syntax

Warning

fn(Key, Found, NotFound, Map) ->
case maps:find(Key,Map) of
{ok, V} -> Found;
error -> NotFound
end.
%% ^^^^^^^^^^^^^^^^^^^^^^^^^^^💡 warning: Unnecessary allocation of result tuple when the key is found.

Explanation

The warning message indicates that a map is being queried by key using the maps:find/2 function call rather than the dedicated lookup syntax.

Whilst this will correctly query for the value for the given key in the map, it is not considered idiomatic, and may be less efficient than using the map lookup syntax directly since it constructs an {ok,Value} tuple if they key is found.

To fix the issue, use the built-in #{Key := Value} pattern syntax to match against the Map:

fn(Key, Found, NotFound, Map) ->
case Map of
#{Key := Value} -> Found;
#{} -> NotFound
end.

The same warning covers the match/assignment idiom, rewriting {ok, Value} = maps:find(Key, Map) into #{Key := Value} = Map.

Correctness

case maps:find(Key, Map) of {ok, Pat} -> ...; error -> ... end raises a case_clause error when the key is present but its value does not match Pat, whereas the empty-map clause #{} -> ... would silently take the not-found branch instead. The case rewrite is therefore only offered when it preserves behaviour: either the fallback is a wildcard _ (which already catches a present-but-unmatched value), or an {ok, Var} clause is unconditional so the ok clauses match every present value. The match idiom has no such caveat — both forms raise badmatch on a miss — so it is rewritten for any value pattern. In both shapes the key must be a legal, non-throwing map-pattern key, so maps:find(compute_key(), Map) is left unchanged.