Credence.Pattern.NoLengthBasedIndexing
(credence v0.6.0)
Copy Markdown
Detects n = length(list) followed by Enum.at(list, n - K) — a Python
list[len(list) - 1] idiom. Elixir's Enum.at/2 natively supports
negative indices, so Enum.at(list, -1) is the idiomatic equivalent.
Detection constraints
Only flags when ALL of:
var = length(list)orvar = Enum.count(list)existsEnum.at(list, var - K)appears in the same block (K is a positive integer literal)- Same list variable in both calls
- No rebinding of either variable between the two calls
Bad
n = length(sorted)
largest = Enum.at(sorted, n - 1)
second_largest = Enum.at(sorted, n - 2)Good
largest = Enum.at(sorted, -1)
second_largest = Enum.at(sorted, -2)Auto-fix
Replaces Enum.at(list, n - K) with Enum.at(list, -K). If the length
variable is only used for indexing, the n = length(list) line is removed.