W0035 - Unnecessary Fold to Build Map
Warning
main(List) ->
lists:foldl(fun(K, Acc) -> Acc#{K => []} end, #{}, List).
%% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 💡 information: Unnecessary explicit fold to construct map from list.
main(List) ->
lists:foldl(fun({K,V}, Acc) -> Acc#{K => V} end, #{}, List).
%% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 💡 information: Unnecessary explicit fold to construct map from list.
Explanation
The warning message indicates an unidiomatic and sub-optimal way to build a map from a list.
Whilst the fold will correctly construct a map from the given list, it is less efficient than it could be, since a BIF exists which can directly construct the required map.
Using the maps:from_keys/2
or maps:from_list/1
BIFs (depending on whether the list
is of just keys or of key-value pairs, respectively), is clearer and more performant.
To fix this warning, the the BIFs from the maps
module to construct your map directly:
main(List) ->
maps:from_list(List). % For lists of key-value pairs
main(List) ->
maps:from_keys(List, []). % For lists of just keys, where every key is given the same value