Map of lists filled by key in a loop
for x in xs: (m[k] ??= []).push(v): let m = xs.group(by: x => k, of: x => v)
let n: 1..=200000 = read()
let a: [0..n]Int = read()
var pos: HashMap<Int, List<Int>> = HashMap()
for i in 0..n:
(pos[a[i] % 3] ??= []).push(i)
print(pos.get(0)?.len ?? 0)let n: 1..=200000 = read()
let a: [0..n]Int = read()
let pos = (0..n).group(by: i => a[i] % 3)
print(pos.get(0)?.len ?? 0)Why
A loop whose only statement is (m[k] ??= []).push(v) sorts elements into lists by a key: xs.group(by: x => k, of: x => v) (std.seq) builds the same HashMap<K, List<V>> in one expression, expected, each list in input order, with no empty-list default to write. Leave out of: when the element itself is pushed. When the key is a domain position, xs.map(k).buckets() gives a [D]List instead of a map. A loop that reads the map while filling it, or pushes only under a condition, is not reported. There is no automatic fix, because group returns a HashMap and a Map the rest of the file walks in key order has to stay one.
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.
// A loop that also reads the map, or pushes under a condition, is doing more than grouping.
let n: 1..=200000 = read()
let a: [0..n]Int = read()
var pos: HashMap<Int, List<Int>> = HashMap()
for i in 0..n:
if a[i] > 0:
(pos[a[i] % 3] ??= []).push(i)
var seen: HashMap<Int, List<Int>> = HashMap()
for i in 0..n:
print(seen.get(a[i])?.len ?? 0)
(seen[a[i]] ??= []).push(i)
print(pos.get(0)?.len ?? 0)Turn it off
For one block, wrap it in with lint(group_into_map: allow):. For a project, add group_into_map = "allow" under [lints] in cp.toml.
Generated from spec/lints/group_into_map, the same record the linter is built from.