chunk_by Groups Consecutive Runs

chunk_by groups consecutive elements whose pairwise predicate holds, turning runs of related values into slices without allocating.

RustData Integrity

Code

rustsnippet
23 lines
// chunk_by 把相邻且谓词成立的元素并成一组:适合游程式数据
fn group_reads(reads: &[i32]) -> Vec<(i32, usize)> {
    reads
        .chunk_by(|a, b| a / 10 == b / 10) // 十位相同算同一段
        .map(|chunk| (chunk[0] / 10, chunk.len()))
        .collect()
}

fn main() {
    let reads = [12, 14, 19, 20, 25, 31, 33];

    for (decade, count) in group_reads(&reads) {
        println!("decade {decade}0s: {count} reads");
    }

    // 谓词只看相邻两个元素:乱序数据不会被强行分组
    let shuffled = [31, 12, 14, 19];
    let sizes: Vec<usize> = shuffled
        .chunk_by(|a, b| a / 10 == b / 10)
        .map(|chunk| chunk.len())
        .collect();
    println!("shuffled group sizes: {sizes:?}");
}

How it works

chunk_by Groups Consecutive Runs reduces to the functions group_reads and main.

Repetition is confined to for (decade, count) in group_reads(&reads) — the rest of the file is straight-line.

Watch out for

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.

Putting it to use

Signature: fn group_reads(reads: &[i32]) -> Vec<(i32, usize)>

Running the file prints labeled results such as decade, shuffled group sizes: — every step leaves its own tagged line.

Execute the file and main walks through group_reads, in that order.

Core lines

fn group_reads(reads: &[i32]) -> Vec<(i32, usize)> {
    reads
        .chunk_by(|a, b| a / 10 == b / 10) // 十位相同算同一段
        .map(|chunk| (chunk[0] / 10, chunk.len()))
        .collect()
}
.map(|chunk| chunk.len())
.collect();

Interactive Tools for This Topic

FAQ

What does chunk_by Groups Consecutive Runs print when run?
No setup needed: run the file and look for labeled lines like `decade`, `shuffled group sizes:` in the output.