Skip to content

Instantly share code, notes, and snippets.

@jkhsjdhjs
Last active August 26, 2019 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkhsjdhjs/ee0f351769664f8bbf625a8cd3ee971c to your computer and use it in GitHub Desktop.
Save jkhsjdhjs/ee0f351769664f8bbf625a8cd3ee971c to your computer and use it in GitHub Desktop.
struct ResultIter<I, F> {
iter: I,
f: F,
}
impl<U, E, R, F, I> Iterator for ResultIter<I, F>
where
I: Iterator<Item = Result<U, E>>,
F: FnOnce(U) -> Result<R, E> + Copy,
{
type Item = Result<R, E>;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|r| r.and_then(self.f))
}
}
trait ResultIterator<U, E> {
fn map_res<R, F>(self, f: F) -> ResultIter<Self, F>
where
F: FnOnce(U) -> Result<R, E>,
Self: Sized;
}
impl<I, U, E> ResultIterator<U, E> for I
where
I: Iterator<Item = Result<U, E>>,
{
fn map_res<R, F>(self, f: F) -> ResultIter<Self, F>
where
F: FnOnce(U) -> Result<R, E>,
Self: Sized,
{
ResultIter { iter: self, f }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment