Skip to main content

W0066 - lists:map/2 to list comprehension

Warning​

main(L) ->
lists:map(fun (X) -> X + 1 end, L).
%% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 💡 warning: lists:map/2 call can be replaced with a list comprehension.

Explanation​

The warning message indicates a lists:map/2 call that can be replaced with a list comprehension. List comprehensions are generally preferred in Erlang because they are more idiomatic, often more readable, and can be more efficient since the compiler can optimize them directly.

To fix this warning, rewrite the lists:map/2 call as a strict list comprehension:

main(L) ->
[X + 1 || X <:- L].

The strict generator (<:-) is used instead of the regular generator (<-) to ensure that the new semantics agree with the pattern matching in the head of the function given to lists:map/2.

Fun References​

This warning also applies to fun Name/Arity syntax:

Local function reference​

main(L) ->
lists:map(fun action/1, L).
%% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 💡 warning: lists:map/2 call can be replaced with a list comprehension.

Can be rewritten as:

main(L) ->
[action(Elem) || Elem <:- L].

Remote function reference​

main(L) ->
lists:map(fun mod:action/1, L).
%% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 💡 warning: lists:map/2 call can be replaced with a list comprehension.

Can be rewritten as:

main(L) ->
[mod:action(Elem) || Elem <:- L].

Function Variables​

This warning also applies when the first argument to lists:map/2 is a variable holding a function:

main(F, L) ->
lists:map(F, L).
%% ^^^^^^^^^^^^^^^^ 💡 warning: lists:map/2 call can be replaced with a list comprehension.

Can be rewritten as:

main(F, L) ->
[F(Elem) || Elem <:- L].