Skip to content

Commit

Permalink
GroupMap: add fold_with (2) more generic init
Browse files Browse the repository at this point in the history
This is a generalization of `fold` which takes a function rather than a
value, which removes the need for a `Clone` bound. `fold` is implemented
in terms of `fold_with`.
  • Loading branch information
tamird authored and phimuemue committed Oct 20, 2023
1 parent 2bf459c commit 7a6c1ef
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 5 deletions.
8 changes: 4 additions & 4 deletions src/grouping_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ where
///
/// let lookup = (1..=7)
/// .into_grouping_map_by(|&n| n % 3)
/// .fold_with(|_key| Default::default(), |Accumulator { acc }, _key, val| {
/// .fold_with(|_key, _val| Default::default(), |Accumulator { acc }, _key, val| {
/// let acc = acc + val;
/// Accumulator { acc }
/// });
Expand All @@ -150,11 +150,11 @@ where
/// ```
pub fn fold_with<FI, FO, R>(self, mut init: FI, mut operation: FO) -> HashMap<K, R>
where
FI: FnMut(&K) -> R,
FI: FnMut(&K, &V) -> R,
FO: FnMut(R, &K, V) -> R,
{
self.aggregate(|acc, key, val| {
let acc = acc.unwrap_or_else(|| init(key));
let acc = acc.unwrap_or_else(|| init(key, &val));
Some(operation(acc, key, val))
})
}
Expand Down Expand Up @@ -189,7 +189,7 @@ where
R: Clone,
FO: FnMut(R, &K, V) -> R,
{
self.fold_with(|_: &K| init.clone(), operation)
self.fold_with(|_, _| init.clone(), operation)
}

/// Groups elements from the `GroupingMap` source by key and applies `operation` to the elements
Expand Down
2 changes: 1 addition & 1 deletion tests/quick.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1481,7 +1481,7 @@ quickcheck! {
let modulo = if modulo == 0 { 1 } else { modulo } as u64; // Avoid `% 0`
let lookup = a.iter().map(|&b| b as u64) // Avoid overflows
.into_grouping_map_by(|i| i % modulo)
.fold_with(|_key| Default::default(), |Accumulator { acc }, &key, val| {
.fold_with(|_key, _val| Default::default(), |Accumulator { acc }, &key, val| {
assert!(val % modulo == key);
let acc = acc + val;
Accumulator { acc }
Expand Down

0 comments on commit 7a6c1ef

Please sign in to comment.