Reputation: 4872
I wrote something which I've been using to combine itertools sort+group.
pub trait SortAndGroup: Iterator {
fn sort_and_group<K>(self, key_selector: fn(&Self::Item) -> K) -> Vec<(K, Vec<Self::Item>)>
where
Self: Sized,
K: Ord,
{
self.sorted_by_key(key_selector)
.group_by(key_selector)
.into_iter()
.map(|(k, g)| (k, g.into_iter().collect::<Vec<_>>()))
.collect::<Vec<_>>()
}
}
impl<T: ?Sized> SortAndGroup for T where T: Iterator { }
I usually want to invoke it on some vec and then do some additional mapping and filtering.
Let's say I use it like this:
files
.iter()
.sort_and_group(|f| f.joint_folder.clone())
.into_iter()
.map(|(joint_folder, g)| {
I'm annoyed that I always have to convert the vec with iter() before calling this and again afterwards call into_iter() on it.
Can I change my trait to have the function callable directly on the Vec and to return something on which I can immediately call map
without having to convert the returned value into iterator?
I want to be able to do something like this:
files
.sort_and_group(|f| f.joint_folder.clone())
.map(|(joint_folder, g)| {
Upvotes: 0
Views: 185