Key tested before += on a map
if k in m: m[k] += v else: m[k] = v: m[k] += v starts a missing key at 0
let n: 1..=100 = read()
let a: [0..n]Int = read()
var cnt: Map<Int, Int> = Map()
for x in a:
if x in cnt:
cnt[x] += 1
else:
cnt[x] = 1
print(cnt)let n: 1..=100 = read()
let a: [0..n]Int = read()
var cnt: Map<Int, Int> = Map()
for x in a:
cnt[x] += 1
print(cnt)Why
C++ code tests m.count(k) before incrementing so the first insert is explicit. On a CP Lang Map, m[k] op= v starts a missing key at the default of the value type (0 for numbers), so m[k] += v is the whole step: the test and the else branch say the same thing twice. For counting a whole sequence, xs.tally() builds the counts in one call. There is no automatic fix yet, because the rewrite is only right when m is a Map.
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.
let n: 1..=100 = read()
let a: [0..n]Int = read()
var cnt: Map<Int, Int> = Map()
for x in a:
if x in cnt:
cnt[x] += 1
else:
cnt[x] = 2
print(cnt)Turn it off
For one block, wrap it in with lint(contains_then_add: allow):. For a project, add contains_then_add = "allow" under [lints] in cp.toml.
Generated from spec/lints/contains_then_add, the same record the linter is built from.