← All lints

loop_reduction

L0504Idiomswarn

Manual accumulation loop

a loop that only accumulates: sum, count, max or min

Flagged
let xs: List<Int> = [1, 2, 3]
var total = 0
for x in xs:
    total += x
print(total)
Write instead
let xs: List<Int> = [1, 2, 3]
let total = sum(x for x in xs)
print(total)

Why

A loop that only sums, counts, or takes a running min/max over an iterable reads more clearly as sum(...), count(...), min(...), or max(...).

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: S.seq: reductions.

Not flagged

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

Near miss
let xs: List<Int> = [1, 2, 3]
var total = 0
for x in xs:
    total += x
    print(total)

Turn it off

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

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