Credence.Pattern.AvoidLengthGuardLessThan2
(credence v0.8.0)
Copy Markdown
Performance rule: Detects function guards that check length(x) < 2 (or
length(x) <= 1) and rewrites them into two O(1) pattern-matched clauses.
length/1 traverses the entire list just to compare with a small number.
When the guard is length(x) < 2, the intent is "zero or one element",
which can be expressed with two pattern-matched clauses that are O(1).
Bad
def maximumdifference(list) when length(list) < 2, do: 0Good
def maximumdifference([]), do: 0
def maximumdifference([_]), do: 0Pattern matching is O(1) and idiomatic, while length/1 is O(n).
Safe core — simple guards only
Fires only when the entire guard is the length comparison. A compound
guard (when length(x) < 2 and P, or ... or P) is left untouched: splitting
it into []/[_] clauses would silently drop P and change behaviour. Those
belong with the sibling no_length_guard_to_pattern (which preserves the
remaining guard), not here.