W0033 - Lists Zip With Seq Rather Than Enumerate
Warning
main(List) ->
lists:zip(lists:seq(1,length(List)),List).
%% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 💡 warning: Unnecessary intermediate list allocated.
main(Start, List) ->
lists:zip(lists:seq(Start,length(List)),List).
%% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 💡 warning: Unnecessary intermediate list allocated.
main(Start, Stride, List) ->
lists:zip(lists:seq(Start,Stride,length(List)),List).
%% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 💡 warning: Unnecessary intermediate list allocated.
Explanation
The warning message indicates that a list (e.g. [a,b,c,...,z]
) is being
enumerated by position to (e.g. [{1,a},{2,b},{3,c},...{26,z}]
)
by creating a parallel list of the index values, which is then zipped with
the input list.
Whilst this will correctly pair each list element with it's index, it is not
considered idiomatic, and unnecessarily constructs an intermediate list of just
the indices (e.g. [1,2,3,...,26]
).
Using lists:enumerate
functions will avoid
constructing an intermediate lists, and hence be more performant. Pick which
overload of lists:enumerate
depending on whether you need to customise the
starting index or stride between index values.
To fix the issue, call lists:enumerate/1
, lists:enumerate/2
or lists:enumerate/3
directly on
the input list:
main(List) ->
lists:enumerate(List).
main(Start, List) ->
lists:enumerate(Start, List).
main(Start, Stride, List) ->
lists:enumerate(Start, Stride, List).