Closed axelkar closed 3 months ago
If we include this, we should think about a generalized version, right? To me, it seems that this basically groups the iterator's items into two categories. If we find an item of the first category, return it right away. If there's no such item, return the last item of the second category. (Please correct me if I got that wrong.)
If that's true, I guess a natural API would be something like this:
fn get_first_satisfying_predicate_or_last_not_satisfying_predicate(self, mut pred: impl FnMut(&Item)->bool) -> Option<Item> {
let mut last_not_satisfying_predicate = None;
for item in self {
if pred(&item) {
return Some(item);
} else {
last_not_satisfying_predicate = Some(item);
}
}
return last_not_satisfying_predicate;
}
That would allow to use it for iterators with arbitrary Item
s.
... which makes me think: Isn't this find_or_last
?
... which makes me think: Isn't this
find_or_last
?
Yes:
fn find_first_ok<T, E, I>(iter: I) -> Result<Option<T>, E>
where
I: IntoIterator<Item = Result<T, E>>,
{
iter.into_iter().find_or_last(|res| res.is_ok()).transpose()
}
Can an example for Results be added to the documentation?
Sure. Could you make a PR?
Sure. Could you make a PR?
Yes
Result<T, E>
Result<Option<T>, E>
This "collector" should return the first
Ok
value it finds asOk(Some(value))
. If noOk
values are found, return the lastErr
. If no values are in the iterator, returnOk(None)
I've written this a couple of times in my own code and figured it'd be useful for Itertools to include.