Skip to main content

W0029 - Unnecessary Reversal To Find Last Element Of List

Error

main(List) ->
hd(lists:reverse(List)).
%% ^^^^^^^^^^^^^^^^^^^^^^^ 💡 warning: Unnecessary intermediate reverse list allocated.

or

main(List) ->
[LastElem|_] = lists:reverse(List),
%% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 💡 warning: Unnecessary intermediate reverse list allocated.
LastElem.

Explanation

The warning message indicates that a list is being unnecessarily reversed.

Whilst this will correctly find the last element of a list, it is unnecessary to construct reverse list to do so.

To fix the issue, use the function lists:last/1 to find the last element without constructing an intermediate, reversed list:

main(List) ->
lists:last(List).