@@ -115,6 +115,50 @@ where
115
115
destination_map
116
116
}
117
117
118
+ /// Groups elements from the `GroupingMap` source by key and applies `operation` to the elements
119
+ /// of each group sequentially, passing the previously accumulated value, a reference to the key
120
+ /// and the current element as arguments, and stores the results in a new map.
121
+ ///
122
+ /// `init` is called to obtain the initial value of each accumulator.
123
+ ///
124
+ /// `operation` is a function that is invoked on each element with the following parameters:
125
+ /// - the current value of the accumulator of the group;
126
+ /// - a reference to the key of the group this element belongs to;
127
+ /// - the element from the source being accumulated.
128
+ ///
129
+ /// Return a `HashMap` associating the key of each group with the result of folding that group's elements.
130
+ ///
131
+ /// ```
132
+ /// use itertools::Itertools;
133
+ ///
134
+ /// #[derive(Debug, Default)]
135
+ /// struct Accumulator {
136
+ /// acc: usize,
137
+ /// }
138
+ ///
139
+ /// let lookup = (1..=7)
140
+ /// .into_grouping_map_by(|&n| n % 3)
141
+ /// .fold_with(|_key| Default::default(), |Accumulator { acc }, _key, val| {
142
+ /// let acc = acc + val;
143
+ /// Accumulator { acc }
144
+ /// });
145
+ ///
146
+ /// assert_eq!(lookup[&0].acc, 3 + 6);
147
+ /// assert_eq!(lookup[&1].acc, 1 + 4 + 7);
148
+ /// assert_eq!(lookup[&2].acc, 2 + 5);
149
+ /// assert_eq!(lookup.len(), 3);
150
+ /// ```
151
+ pub fn fold_with < FI , FO , R > ( self , mut init : FI , mut operation : FO ) -> HashMap < K , R >
152
+ where
153
+ FI : FnMut ( & K ) -> R ,
154
+ FO : FnMut ( R , & K , V ) -> R ,
155
+ {
156
+ self . aggregate ( |acc, key, val| {
157
+ let acc = acc. unwrap_or_else ( || init ( key) ) ;
158
+ Some ( operation ( acc, key, val) )
159
+ } )
160
+ }
161
+
118
162
/// Groups elements from the `GroupingMap` source by key and applies `operation` to the elements
119
163
/// of each group sequentially, passing the previously accumulated value, a reference to the key
120
164
/// and the current element as arguments, and stores the results in a new map.
@@ -140,15 +184,12 @@ where
140
184
/// assert_eq!(lookup[&2], 2 + 5);
141
185
/// assert_eq!(lookup.len(), 3);
142
186
/// ```
143
- pub fn fold < FO , R > ( self , init : R , mut operation : FO ) -> HashMap < K , R >
187
+ pub fn fold < FO , R > ( self , init : R , operation : FO ) -> HashMap < K , R >
144
188
where
145
189
R : Clone ,
146
190
FO : FnMut ( R , & K , V ) -> R ,
147
191
{
148
- self . aggregate ( |acc, key, val| {
149
- let acc = acc. unwrap_or_else ( || init. clone ( ) ) ;
150
- Some ( operation ( acc, key, val) )
151
- } )
192
+ self . fold_with ( |_: & K | init. clone ( ) , operation)
152
193
}
153
194
154
195
/// Groups elements from the `GroupingMap` source by key and applies `operation` to the elements
0 commit comments