Skip to content

Add fold_mut alternative to fold #481

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,7 @@ harness = false
[[bench]]
name = "bench1"
harness = false

[[bench]]
name = "fold_mut"
harness = false
109 changes: 109 additions & 0 deletions benches/fold_mut.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use itertools::Itertools;

fn bench_sum(c: &mut Criterion) {
let mut group = c.benchmark_group("fold sum accumulator");

group.bench_function("fold", |b| {
b.iter(|| {
(0i64..1_000_000)
.map(black_box)
.fold(0, |sum, n| sum + n)
})
});

group.bench_function("fold_mut", |b| {
b.iter(|| {
(0i64..1_000_000).map(black_box).fold_mut(0, |sum, n| {
*sum += n;
})
})
});

group.finish();
}

fn bench_vec(c: &mut Criterion) {
let mut group = c.benchmark_group("fold vec accumulator");

group.bench_function("fold", |b| {
b.iter(|| {
(0i64..1_000_000)
.map(black_box)
.fold(Vec::new(), |mut v, n| {
v.push(n);
v
})
})
});

group.bench_function("fold_mut", |b| {
b.iter(|| {
(0i64..1_000_000)
.map(black_box)
.fold_mut(Vec::new(), |v, n| {
v.push(n);
})
})
});

group.finish();
}

fn bench_num_with_chain(c: &mut Criterion) {
let mut group = c.benchmark_group("fold chained iterator with num accumulator");

group.bench_function("fold", |b| {
b.iter(|| {
(0i64..1_000_000)
.chain(0i64..1_000_000)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a benchmark with chain to show that, because fold_mut uses for_each, it benefits from Chain's specialization of fold

.map(black_box)
.fold(0, |sum, n| sum + n)
})
});

group.bench_function("fold_mut", |b| {
b.iter(|| {
(0i64..1_000_000)
.chain(0i64..1_000_000)
.map(black_box)
.fold_mut(0, |sum, n| {
*sum += n;
})
})
});

group.finish();
}

fn bench_vec_with_chain(c: &mut Criterion) {
let mut group = c.benchmark_group("fold chained iterator with vec accumulator");

group.bench_function("fold", |b| {
b.iter(|| {
(0i64..1_000_000)
.chain(0i64..1_000_000)
.map(black_box)
.fold(Vec::new(), |mut v, n| {
v.push(n);
v
})
})
});

group.bench_function("fold_mut", |b| {
b.iter(|| {
(0i64..1_000_000)
.chain(0i64..1_000_000)
.map(black_box)
.fold_mut(Vec::new(), |v, n| {
v.push(n);
})
})
});

group.finish();
}

criterion_group!(benches, bench_sum, bench_vec, bench_num_with_chain, bench_vec_with_chain);
criterion_main!(benches);
40 changes: 40 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2831,6 +2831,46 @@ pub trait Itertools : Iterator {
self.for_each(|item| *counts.entry(item).or_default() += 1);
counts
}

/// An alternative to [`fold()`] - `fold_mut()` also applies a function
/// producing a single value. The main difference is that the closure
/// passed to `fold_mut()` accepts a `&mut` to the accumulator instead
/// of consuming the accumulator. This can simplify some closures
/// that might otherwise be forced to return the accumulator awkwardly:
/// ```
/// let evens = [1, 2, 3, 4, 5, 6].iter().fold(Vec::new(), |mut evens, num| {
/// if num % 2 == 0 {
/// evens.push(num);
/// }
/// evens // potentially awkward return
/// });
/// ```
///
/// `fold_mut()` may also be more performant in situations where the
/// accumulator is "large" as passing it by `&mut` can be cheaper than moving it.
///
/// # Examples
/// ```
/// # use itertools::Itertools;
/// let evens = [1, 2, 3, 4, 5, 6].iter().fold_mut(Vec::new(), |evens, &num| {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this example too lame? I was going to use the example of counting but ... there's .counts right above this so that seemed worse haha

/// if num % 2 == 0 {
/// evens.push(num);
/// }
/// });
///
/// assert_eq!(evens, [2, 4, 6]);
/// ```
/// [`fold()`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.fold
#[cfg(feature = "use_std")]
fn fold_mut<B, F>(self, init: B, mut f: F) -> B
where
Self: Sized,
F: FnMut(&mut B, Self::Item),
{
let mut accum = init;
self.for_each(|item| f(&mut accum, item));
accum
}
}

impl<T: ?Sized> Itertools for T where T: Iterator { }
Expand Down
21 changes: 21 additions & 0 deletions tests/quick.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1237,3 +1237,24 @@ quickcheck! {
TestResult::from_bool(itertools::equal(x, y))
}
}

quickcheck! {
fn test_fold_mut(a: Vec<u8>) -> TestResult {
let with_fold_mut =
a.iter().fold_mut(Vec::new(), |v, &n| {
if n % 2 == 0 {
v.push(n);
}
});

let with_fold =
a.iter().fold(Vec::new(), |mut v, &n| {
if n % 2 == 0 {
v.push(n);
}
v
});

TestResult::from_bool(itertools::equal(with_fold_mut, with_fold))
}
}