← All lints

sort_desc_by_negation

L0541Idiomswarn

descending sort by a negated key

sorted(by: x => -x): sorted(desc: true) says it and never overflows

Flagged
let n: 1..=100 = read()
let a: [0..n]Int = read()
print(a.sorted(by: x => -x))
Write instead
let n: 1..=100 = read()
let a: [0..n]Int = read()
print(a.sorted(desc: true))

Why

C++ sorts descending with greater<>() or by negating the key, and code translated from it writes xs.sorted(by: x => -x). Negating the key hides the intent and overflows on the smallest value of the type. sort and sorted take desc: true, which reverses the order with the key unchanged. The fix applies when the key is exactly the negated element; for a negated field or expression, the help suggests keeping the key and adding desc: true.

The practice it serves

A hand-written pattern the language or the standard library already says in one step.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let n: 1..=100 = read()
let a: [0..n]Int = read()
print(a.sorted(by: x => x % 7))

Turn it off

For one block, wrap it in with lint(sort_desc_by_negation: allow):. For a project, add sort_desc_by_negation = "allow" under [lints] in cp.toml.

Generated from spec/lints/sort_desc_by_negation, the same record the linter is built from.