Description
This is a very simple proposition to add a find_map
trait method to the Iterator
trait.
It would look like this :
fn find_map<B, P>(&mut self, predicate: P) -> Option<B> where P: FnMut(&Self::Item) -> Option<B>;
Currently to reproduce similar behavior, one would have to use a combination of filter_map
and next
. It is obvious for the Rust connoisseur that is aware that an Iterator is lazy and will not do anything unless consumed, but it much less obvious for the standard programmer that doesn't think this way yet.
Let's take an example :
#[derive(Debug,Copy,Clone)]
enum Flavor {
Chocolate,
Strawberry,
Cherry
}
#[derive(Debug,Copy,Clone)]
enum Dessert {
Banana,
Pudding,
Cake(Flavor)
}
fn main() {
let desserts_of_the_week = vec![
Dessert::Banana,
Dessert::Cake(Flavor::Chocolate),
Dessert::Pudding,
Dessert::Pudding,
Dessert::Pudding,
];
}
If I want to have the "flavor of the cake of the week", as an Option<Flavor>
, a non-newbie Rust user will use this :
let cake_of_the_week : Option<Flavor> = desserts_of_the_week.iter().filter_map(|dessert|{
match dessert {
&Dessert::Cake(ref flavor) => Some(flavor.clone()),
_ => None
}
}).next();
However a new user will be tempted to do something like this :
let cake_of_the_week : Option<Flavor> = desserts_of_the_week.iter().find(|dessert|{
match dessert {
&&Dessert::Cake(_) => true,
_ => false
}
}).map(|dessert|{
match dessert {
&Dessert::Cake(ref flavor) => flavor.clone(),
_ => unreachable!()
}
});
That is why I propose to add a find_map
method to the Iterator trait, which would
- Reduce a little bit your code and increase readability (in the case of
filter_map(...).next()
- Avoid new users to code in a non-idiomatic way
It would then look like this :
let cake_of_the_week : Option<Flavor> = desserts_of_the_week.iter().find_map(|dessert|{
match dessert {
&Dessert::Cake(ref flavor) => Some(flavor.clone()),
_ => None
}
});
There aren't that much advantages, but I still do think it's worth the while to add such a method.
Maybe this has been discussed before, in that case I'd appreciate a link to some discussion related to this topic, because I could not find anything.
Thoughts ?