trait VecMap<T>: IntoIterator<Item = T> + Sized {
#[inline]
fn map<U, F: FnMut(T) -> U>(self, f: F) -> core::iter::Map<Self::IntoIter, F> {
self.into_iter().map(f)
}
#[inline]
fn map_to_vec<U, F: FnMut(T) -> U>(self, f: F) -> Vec<U> {
self.into_iter().map(f).collect()
}
}
impl<T> VecMap<T> for Vec<T> {}
trait MapMap<K, V>: IntoIterator<Item = (K, V)> + Sized {
#[inline]
fn map<U, F: FnMut((K, V)) -> U>(self, f: F) -> core::iter::Map<Self::IntoIter, F> {
self.into_iter().map(f)
}
#[inline]
fn map_to_vec<U, F: FnMut((K, V)) -> U>(self, f: F) -> Vec<U> {
self.into_iter().map(f).collect()
}
}
impl<K, V> MapMap<K, V> for std::collections::HashMap<K, V> {}
impl<K, V> MapMap<K, V> for std::collections::BTreeMap<K, V> {}
impl<K, V> MapMap<K, V> for indexmap::IndexMap<K, V> {}
trait OptionToVec<T>: IntoIterator<Item = T> + Sized {
#[inline]
fn to_vec(self) -> Vec<T> {
self.into_iter().collect()
}
}
impl<T> OptionToVec<T> for Option<T> {}
Having a quick access to map
raises question why not also filter
, and why not everything else on the Iterator
?
5 Likes
If you find yourself repeating this pattern very often you can solve it in a few less lines of code
trait MagicMap<T>: IntoIterator<Item=T> + Sized {
fn magic_map<U, F: FnMut(T) -> U, C>(self, f: F) -> C where C: FromIterator<U> {
self.into_iter().map(f).collect()
}
}
impl<T, X: IntoIterator<Item=T>> MagicMap<T> for X {}
However, in my opinion this is not something to encourage in general. What is your motivation for less into_iter
and collect
?
5 Likes
map
is just an example (and a case I actually encountered).
Agreed.
Maybe consider making a crate.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.