← All lints

count_until

L0562Idiomswarn

Step counter searched by hand

while p < n: p *= 3; k += 1: (0..).find(k => 3 ** k >= n)! names the smallest k

Flagged
fn ceil_log3(n: Int) -> Int:
    var p = 1
    var k = 0
    while p < n:
        p *= 3
        k += 1
    k

let n: 1..=1000000000 = read()
print(ceil_log3(n))
Write instead
fn ceil_log3(n: Int) -> Int = (0..).find(k => 3 ** k >= n)!

let n: 1..=1000000000 = read()
print(ceil_log3(n))

Why

A loop that steps a value (p *= 3 or p += c) and counts the steps until a condition fails is a search for the smallest step count k where the condition fails. The value after k steps has a closed form (p0⋅ckp_0 \cdot c^k or p0+ckp_0 + c k), so (0..).find(k => 3 ** k >= n)! says what is wanted, the smallest k with 3k≥n3^k \ge n, in one line and without two counters to keep in step. If the loop's value is still needed afterwards, it is the closed form at that k. A step that is not a plain multiply or add, such as x = (x + 1) / 2, has no closed form and is not reported. There is no automatic fix, because the counter's other uses have to be read.

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
fn halvings(n: Int) -> Int:
    var x = n
    var k = 0
    while x > 1:
        x = (x + 1) / 2
        k += 1
    k

let n: 1..=1000000000 = read()
print(halvings(n))

Turn it off

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

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