#iterable #reduction #pattern #nested #abstraction #generic #combining

reductor

Generic abstractions for combining and nesting reduction patterns for iterables

13 releases

0.0.12 Mar 26, 2024
0.0.11 Mar 26, 2024
0.0.10 Oct 2, 2022
0.0.9 Aug 6, 2022
0.0.4 Aug 22, 2021

#725 in Rust patterns

23 downloads per month

MIT/Apache

27KB
502 lines

reductor

Generic abstractions for combining and nesting reduction patterns for iterables.

Docs: https//docs.rs/reductor

Before & After:

Before

fn process_samples(
    samples: &[i32],
    scale: &[i32],
    upper_limit: i32
) {
    let mut sum = 0;
    let mut min = None;
    let mut max = None;

    for (sample, scale) in samples.iter().zip(scale) {
        let scaled = sample * scale;

        if scaled <= upper_limit {
            continue;
        }

        sum += scaled;
        min = Some(match min {
            Some(min) => scaled.min(min),
            None => scaled,
        });
        max = Some(match max {
            Some(max) => scaled.max(max),
            None => scaled,
        });
    }

    // ...
}

After

use reductor::{Reduce, Reductors, Sum, Min, Max};

fn process_samples(
    samples: &[i32],
    scale: &[i32],
    upper_limit: i32
) {
    let Reductors((Sum::<i32>(sum), Min::<Option<i32>>(min), Max::<Option<i32>>(max))) = samples
        .iter()
        .zip(scale)
        .map(|(sample, scale)| sample * scale)
        .filter(|&scaled| scaled <= upper_limit)
        .reduce_with();

    // ...
}

No runtime deps