← All lints

hand_rolled_gcd

L0546Idiomswarn

hand-rolled gcd

f(b, a % b): gcd(a, b) is in std.math

Flagged
let (a, b): (1..=1000000000, 1..=1000000000) = read()
fn g(x: Int, y: Int) -> Int:
    if y == 0:
        return x
    return g(y, x % y)
print(g(a, b))
Write instead
let (a, b): (1..=1000000000, 1..=1000000000) = read()
print(gcd(a, b))

Why

Euclid's algorithm, a function that calls itself as f(b, a % b), is gcd(a, b) from std.math (in the prelude), and the gcd of a list is xs.fold(gcd, 0). The lint fires on a two-parameter function that recurses this way. There is no automatic fix, since the call replaces the whole function.

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 (a, b): (1..=1000000000, 1..=1000000000) = read()
fn g(x: Int, y: Int) -> Int:
    if y == 0:
        return x
    return g(y, x - y)
print(g(a, b))

Turn it off

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

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