Skip to main content

W0065 - Prefer pattern matching over length check

Warning

check_list(List) ->
case length(List) of 0 -> empty; _ -> non_empty end.
%% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 💡 warning: W0065: Use pattern matching on the list directly instead of checking length.

Explanation

The warning indicates that you are using length/1 to check if a list is empty or non-empty. This is inefficient because length/1 traverses the entire list to compute its length, making it O(n) where n is the number of elements.

When you only need to distinguish between an empty list and a non-empty list, pattern matching on the list structure is more efficient and idiomatic.

N.B. If the intention is to validate whether the value is a proper list or not - i.e. whether the last cons cell points to the empty list, then do not apply this rewriting and explicitly ignore it as intentional instead, with % elp:ignore W0065 Intentionally traversing all elements to validate that is it is not an improper list.

Detected Patterns

This diagnostic detects the following patterns:

  • case length(List) of 0 -> ...; _ -> ... end
  • case length(List) =:= 0 of true -> ...; false -> ... end
  • case length(List) =/= 0 of true -> ...; false -> ... end
  • case length(List) > 0 of true -> ...; false -> ... end
  • case length(List) >= 1 of true -> ...; false -> ... end

Why This Matters

  • Idiomatic Erlang: Pattern matching on list structure is the standard Erlang way to check for empty/non-empty lists.
  • Performance: length/1 traverses the entire list, making it O(n). Pattern matching on [] is O(1).

Fix

Replace the length check with pattern matching directly on the list:

check_list(List) ->
case List of [] -> empty; _ -> non_empty end.