Skip to main content

W0096 - Map comprehension can be replaced with maps:from_keys/2

Warning​

fn(List) -> #{K => true || K <- List}.
%% ^^^^^^^^^^^^^^^^^^^^^^^^^^ 💡 weak: W0096: Map comprehension can be replaced with a call to maps:from_keys/2.

Explanation​

The map comprehension gives the same value to each element of the list.

The maps:from_keys/2 BIF builds the same map directly from the list. The comprehension first builds an intermediate list, so it is slower and allocates more memory.

The warning only applies when the generator pattern is a plain variable, there are no filters, the generator expression binds no variables (they are local to the comprehension, but not to a call argument), and the value does not depend on the generator variable. The value must also be safe to evaluate once, even for an empty list: a variable, a literal, a signed number such as -1, a binary of string, integer or character literals without size, unit or type, or a tuple, list or map of those, directly, in parentheses or through a macro.

To fix this warning, replace the comprehension with a call to maps:from_keys/2:

fn(List) -> maps:from_keys(List, true).