Skip to content

Commit 4396c74

Browse files
tamirdphimuemue
authored andcommitted
GroupMap: add fold_with (2) more generic init
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`.
1 parent 2bf459c commit 4396c74

File tree

2 files changed

+5
-5
lines changed

2 files changed

+5
-5
lines changed

src/grouping_map.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ where
138138
///
139139
/// let lookup = (1..=7)
140140
/// .into_grouping_map_by(|&n| n % 3)
141-
/// .fold_with(|_key| Default::default(), |Accumulator { acc }, _key, val| {
141+
/// .fold_with(|_key, _val| Default::default(), |Accumulator { acc }, _key, val| {
142142
/// let acc = acc + val;
143143
/// Accumulator { acc }
144144
/// });
@@ -150,11 +150,11 @@ where
150150
/// ```
151151
pub fn fold_with<FI, FO, R>(self, mut init: FI, mut operation: FO) -> HashMap<K, R>
152152
where
153-
FI: FnMut(&K) -> R,
153+
FI: FnMut(&K, &V) -> R,
154154
FO: FnMut(R, &K, V) -> R,
155155
{
156156
self.aggregate(|acc, key, val| {
157-
let acc = acc.unwrap_or_else(|| init(key));
157+
let acc = acc.unwrap_or_else(|| init(key, &val));
158158
Some(operation(acc, key, val))
159159
})
160160
}
@@ -189,7 +189,7 @@ where
189189
R: Clone,
190190
FO: FnMut(R, &K, V) -> R,
191191
{
192-
self.fold_with(|_: &K| init.clone(), operation)
192+
self.fold_with(|_, _| init.clone(), operation)
193193
}
194194

195195
/// Groups elements from the `GroupingMap` source by key and applies `operation` to the elements

tests/quick.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1481,7 +1481,7 @@ quickcheck! {
14811481
let modulo = if modulo == 0 { 1 } else { modulo } as u64; // Avoid `% 0`
14821482
let lookup = a.iter().map(|&b| b as u64) // Avoid overflows
14831483
.into_grouping_map_by(|i| i % modulo)
1484-
.fold_with(|_key| Default::default(), |Accumulator { acc }, &key, val| {
1484+
.fold_with(|_key, _val| Default::default(), |Accumulator { acc }, &key, val| {
14851485
assert!(val % modulo == key);
14861486
let acc = acc + val;
14871487
Accumulator { acc }

0 commit comments

Comments
 (0)