← All lints

map_as_multiset

L0563Idiomswarn

Map used as a multiset

cnt[x] += 1 / if cnt[x] > 0: cnt[x] -= 1: SortedBag<K> (std.bag)

Flagged
let q: 1..=200000 = read()
var cnt: Map<Int, Int> = Map()
for _ in 0..q:
    let (t, x): (1..=2, 1..=1000000000) = read()
    if t == 1:
        cnt[x] += 1
    elif cnt[x] > 0:
        cnt[x] -= 1
print(cnt.len)
Write instead
let q: 1..=200000 = read()
var bag = SortedBag<Int>()
for _ in 0..q:
    let (t, x): (1..=2, 1..=1000000000) = read()
    if t == 1:
        bag.add(x)
    else:
        bag.remove(x)
print(bag.len)

Why

A Map<K, Int> whose entries go up by one and down by one, with the decrement guarded by cnt[x] > 0, is a multiset kept by hand, C++'s map<int, int> with cnt[x]++ and cnt[x]--. SortedBag<K> (std.bag, in the prelude) is that multiset: bag.add(x) adds a copy, bag.remove(x) removes one and is false when there is none, bag.count(x) is the number of copies, and bag.first / bag.last are the smallest and largest, which the map can only find by scanning. A counting map that only goes up (a frequency table) is not reported. There is no automatic fix, since the reads of the counts change with the type.

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: S.sorted: sets, bags, maps, intervals.

Not flagged

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

Near miss
let n: 1..=200000 = read()
let a: [0..n]Int = read()
var cnt: Map<Int, Int> = Map()
for x in a:
    cnt[x] += 1
print(cnt.len)

Turn it off

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

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