← All lints

hand_rolled_answer_search

L0520Idiomswarn

Hand-rolled binary search

manual while lo < hi midpoint loop over a predicate: use r.first_true/r.last_true

Flagged
let a = [1, 3, 5, 7]
var (lo, hi) = (0, a.len)
while lo < hi:
    let mid = (lo + hi) / 2
    if a[mid] >= 5: hi = mid else: lo = mid + 1
print(lo)
Write instead
let a = [1, 3, 5, 7]
let lo = (0..a.len).first_true(mid => a[mid] >= 5) ?? a.len
print(lo)

Why

A while lo < hi loop that halves with let mid = (lo + hi) / 2 and sets hi = mid / lo = mid + 1 (or lo = mid / hi = mid - 1 with the rounded-up midpoint) on a predicate of mid is r.first_true(ok) (or r.last_true(ok)) on its range: O(log⁡n)O(\log n) calls of the predicate, no off-by-one in the bounds, and the same midpoint that cannot overflow. cpl fix rewrites the loop and its var (lo, hi) when hi is not read after it. The predicate must be monotone along the range, which the loop already assumes.

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: S.search: binary and ternary search.

Not flagged

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

Near miss
let a = [1, 3, 5, 7]
var (lo, hi) = (0, a.len)
while lo < hi:
    lo += 1
    hi -= 1
print(lo)

Turn it off

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

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