Closed rodrigocfd closed 3 months ago
A more general API would be
let position: Result<usize, _> = iter.try_and(|it| it.position(|e| e == "bar"));
Previous conversation: https://github.com/rust-lang/rfcs/pull/3233#discussion_r815183078
itertools::process_results
/ Itertools::process_results
are offshoots of the original shunt code that I added to the standard library. Both versions have evolved since then, but presumably still solve the same core issue.
use itertools::Itertools; // 0.12.1
fn main() {
let v = [Ok::<u8, ()>(1), Ok(3)]
.into_iter()
.process_results(|mut i| i.all(|i| i > 2));
assert_eq!(Ok(false), v);
let v = [Ok::<u8, ()>(1), Ok(3)]
.into_iter()
.process_results(|mut i| i.position(|i| i > 2));
assert_eq!(Ok(Some(1)), v);
}
We discussed this in the libs-api meeting and we are happy to add these. However these should be based on the Try
trait to allow them to work with both Option
and Result
. Additionally, the implementation should use try_fold
internally since many iterators will specialize that method for better performance. Finally, stabilization of these will likely be blocked on the stabilization of the Try
trait, like most other methods using that trait.
Feel free to open a tracking issue and open a PR to rust-lang/rust to add it as an unstable feature.
@Amanieu where I can find information about this Try
trait?
Have a look at the existing try_find
and try_reduce
methods on the Iterator
trait.
Finally, stabilization of these will likely be blocked on the stabilization of the
Try
trait, like most other methods using that trait.
Note that try_all
and try_any
will be blocked only on Try
, but try_(r)position
will also be blocked on Residual
, like how try_find
is blocked on it.
Proposal
Problem statement
Currently there is no simple way to use
all()
,any()
,position()
andrposition()
if the predicate can fail, returning anErr
.Motivating examples or use cases
This proposal came from an StackOverflow question, which asks for a fallible method for
position()
. The answer is rather convoluted when compared to the simplicity oftry_for_each()
versusfor_each()
.The original question is:
Solution sketch
I sketched a
FooIterator
with the aforementioned methods so I could use them right away, but I suppose they should be members ofIterator
. Also, I'm aware the implementation below is far from being standardized:Alternatives
I implemented and published the
TryIterator
crate, so I could use these methods immediately. But I believe these methods have their place in the standard library.