W0056 - Use lists:reverse/2 instead of lists:reverse/1 ++ Tail
Warning
reverse_and_append(List, Tail) ->
lists:reverse(List) ++ Tail.
%% ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 💡 warning: W0056: Use `lists:reverse/2` instead of `lists:reverse/1 ++ Tail` for better performance.
Explanation
The warning indicates that you are using the pattern lists:reverse(List) ++ Tail, which is inefficient. This pattern first reverses the list, creating an intermediate reversed list, and then appends the tail to it using the ++ operator.
The Erlang standard library provides a more efficient function lists:reverse/2 that performs both operations in a single pass without creating the intermediate reversed list.
Why This Matters
- Performance: Using
lists:reverse/1followed by++creates an unnecessary intermediate data structure - Memory: The intermediate reversed list consumes additional memory that is immediately discarded
- Idiomatic Erlang:
lists:reverse/2is the idiomatic way to reverse and prepend in Erlang
Fix
Replace the pattern with lists:reverse/2:
reverse_and_append(List, Tail) ->
lists:reverse(List, Tail).
How lists:reverse/2 Works
The second argument to lists:reverse/2 acts as an accumulator that gets prepended to the reversed list:
lists:reverse([1, 2, 3], [4, 5, 6]).
% Returns: [3, 2, 1, 4, 5, 6]
This is equivalent to lists:reverse([1, 2, 3]) ++ [4, 5, 6] but significantly more efficient.