Heap popped a fixed number of times by hand
for _ in 0..k: using h.pop()!: for x in h.drain().take(k)
let (n, k): (1..=200000, 1..=200000) = read()
let a: [0..n]Int = read()
var h = MaxHeap<Int>()
for x in a: h.push(x)
for _ in 0..min(k, n):
print(h.pop()!, end: " ")let (n, k): (1..=200000, 1..=200000) = read()
let a: [0..n]Int = read()
var h = MaxHeap<Int>()
for x in a: h.push(x)
for x in h.drain().take(k):
print(x, end: " ")Why
for _ in 0..k: with h.pop()! in the body takes the top k elements of a heap one by one, and traps when the heap holds fewer than k. for x in h.drain().take(k) (std.heap) yields the same elements in the same order, names each one, and stops early when the heap runs out; for x in h.drain() takes them all. Each pop is either way. A loop that pushes into the heap it pops (merging, simulation) is not reported. There is no automatic fix, because the popped value has to be named where the body uses it.
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 pushes back into the heap it pops is a simulation, not a drain.
let (n, k): (1..=200000, 1..=200000) = read()
let a: [0..n]Int = read()
var h = MinHeap<Int>()
for x in a: h.push(x)
for _ in 0..min(k, n - 1):
let x = h.pop()!
let y = h.pop()!
h.push(x + y)
print(h.pop()!)
// Nor is one that calls a helper refilling the heap.
var g = MaxHeap<Int>()
fn refill(x: Int):
if x > 1: g.push(x / 2)
for x in a: g.push(x)
var total = 0
for _ in 0..k:
let x = g.pop()!
total += x
refill(x)
print(total)Turn it off
For one block, wrap it in with lint(manual_heap_drain: allow):. For a project, add manual_heap_drain = "allow" under [lints] in cp.toml.
Generated from spec/lints/manual_heap_drain, the same record the linter is built from.