Smaller set merged into the larger by hand
if a.len < b.len: (a, b) = (b, a) then for x in b: a.add(x): a.absorb(mut b)
let (n, q): (1..=100000, 1..=100000) = read()
var sets: List<SortedSet<Int>> = [SortedSet.of([x]) for x in 0..n]
var id: List<Int> = [x for x in 0..n]
for _ in 0..q:
let (x, y): (0..n, 0..n) = read()
if x == y:
continue
var big = id[x]
var small = id[y]
if sets[big].len < sets[small].len:
(big, small) = (small, big)
for w in sets[small]:
sets[big].add(w)
sets[small] = SortedSet.of([])
id[x] = big
id[y] = small
print(sets[big].len)let (n, q): (1..=100000, 1..=100000) = read()
var sets: List<SortedSet<Int>> = [SortedSet.of([x]) for x in 0..n]
for _ in 0..q:
let (x, y): (0..n, 0..n) = read()
if x == y:
continue
sets[x].absorb(mut sets[y])
print(sets[x].len)Why
Merging two sets by first swapping so the smaller one is walked, then adding its elements to the larger, is small-to-large merging: each element moves times over any sequence of merges. Written by hand it is a length test, a swap of two names, a loop, and the bookkeeping of which name now holds the union. a.absorb(mut b) does the same: it swaps the contents when a is the smaller, adds the rest, and leaves b empty, so a always ends up with the union. It exists on SortedSet, SortedBag, SortedMap (with a join: for equal keys), FlatMap, Counter and MeldHeap. There is no automatic fix, since code after the loop may still read the swapped names. A swap by length followed by something other than adding each element (adding two lists position by position) is not reported.
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..=100000 = read()
var xs: List<Int> = [2 * x for x in 0..n]
var ys: List<Int> = [x for x in 0..n / 2]
if xs.len < ys.len:
(xs, ys) = (ys, xs)
for i in 0..ys.len:
xs[i] += ys[i]
print(xs)Turn it off
For one block, wrap it in with lint(small_to_large_by_hand: allow):. For a project, add small_to_large_by_hand = "allow" under [lints] in cp.toml.
Generated from spec/lints/small_to_large_by_hand, the same record the linter is built from.