Hand-rolled prefix sum
manual p[i + 1] = p[i] + x or p[i.r] = p[i.l] + x loop: use Prefix(...)
let a = [1, 2, 3, 4]
var p = List.filled(a.len + 1, 0)
for i in 0..a.len:
p[i + 1] = p[i] + a[i]
print(p[3] - p[1])let a = [1, 2, 3, 4]
let p = Prefix(a)
print(p.prefix(3) - p.prefix(1))Why
A loop that fills a prefix-sum array (p[i + 1] = p[i] + x, p[i] = p[i - 1] + x, p[i.r] = p[i.l] + x, or the 2D inclusion-exclusion recurrence) duplicates Prefix(...) in std.prefix (prelude). Prefix owns the extra boundary slot and gives .sum(range) and .prefix(cut) without off-by-one indexing. cpl fix rewrites a zero-initialized declaration, its build loop, and subsequent p[k] reads into let p = Prefix(...) and p.prefix(k) when p is not mutated again.
The practice it serves
A hand-written pattern the language or the standard library already says in one step. Family: S.prefix: prefix, difference and sliding structures.
Not flagged
A near miss: close to the pattern, but not it.
let a = [1, 2, 3, 4]
var p = List.filled(a.len + 1, 0)
for i in 0..a.len:
p[i + 1] = max(p[i], a[i])
print(p[3])
// A running total walked whole: a `Prefix` has no `any`, so the loop stays.
var pre: List<Int> = []
var run = 0
for x in a:
run += x
pre.push(run)
print(yes(pre.any(t => t > 5)))Turn it off
For one block, wrap it in with lint(hand_rolled_prefix_sum: allow):. For a project, add hand_rolled_prefix_sum = "allow" under [lints] in cp.toml.
Generated from spec/lints/hand_rolled_prefix_sum, the same record the linter is built from.