Credence.Pattern.NoSortForTopK (credence v0.7.0)

Copy Markdown

Detects inefficient patterns where a full sort is performed only to retrieve the minimum or maximum element via Enum.at(0).

Sorting an entire collection is O(n log n). When only the minimum or maximum element is needed, Enum.min/Enum.max provides the same result in O(n) without allocating a sorted intermediate list. The fn -> nil end empty_fallback preserves Enum.at(0)'s nil-on-empty behaviour (bare Enum.min/1 would raise Enum.EmptyError).

Flagged patterns

PatternSuggested replacement

| Enum.sort/1 |> Enum.at(0) | Enum.min(_, fn -> nil end) | | Enum.sort/1 |> Enum.reverse() |> Enum.at(0) | Enum.max(_, fn -> nil end) |

Only the Enum.at(0) terminal is rewritten. The Enum.take(1) and hd/1 terminals are deliberately not fixed: take(1) returns a one-element list ([min]), not the scalar Enum.min/1 returns; and hd([]) raises ArgumentError where Enum.min([]) raises Enum.EmptyError — neither is behaviour-preserving.

Bad

Enum.sort(list) |> Enum.at(0)
Enum.sort(list) |> Enum.reverse() |> Enum.at(0)

Good

Enum.min(list, fn -> nil end)
Enum.max(list, fn -> nil end)