From db0d70e58f2a5d42e52f2540af02d14591602717 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Mon, 4 May 2020 11:25:54 -0700 Subject: [PATCH] Refactor `try_find` a little The `E` type parameter was unnecessary, so it's now removed. The folding closure now has reduced parametricity on just `T = Self::Item`, rather than the whole `Self` iterator type. There's otherwise no functional change in this. --- src/libcore/iter/traits/iterator.rs | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/libcore/iter/traits/iterator.rs b/src/libcore/iter/traits/iterator.rs index fbfcdc3c1a9ea..530cf881f29da 100644 --- a/src/libcore/iter/traits/iterator.rs +++ b/src/libcore/iter/traits/iterator.rs @@ -2265,7 +2265,7 @@ pub trait Iterator { } /// Applies function to the elements of iterator and returns - /// the first non-none result or the first error. + /// the first true result or the first error. /// /// # Examples /// @@ -2286,19 +2286,26 @@ pub trait Iterator { /// ``` #[inline] #[unstable(feature = "try_find", reason = "new API", issue = "63178")] - fn try_find(&mut self, mut f: F) -> Result, E> + fn try_find(&mut self, f: F) -> Result, R::Error> where Self: Sized, F: FnMut(&Self::Item) -> R, - R: Try, - { - self.try_fold((), move |(), x| match f(&x).into_result() { - Ok(false) => LoopState::Continue(()), - Ok(true) => LoopState::Break(Ok(x)), - Err(x) => LoopState::Break(Err(x)), - }) - .break_value() - .transpose() + R: Try, + { + #[inline] + fn check(mut f: F) -> impl FnMut((), T) -> LoopState<(), Result> + where + F: FnMut(&T) -> R, + R: Try, + { + move |(), x| match f(&x).into_result() { + Ok(false) => LoopState::Continue(()), + Ok(true) => LoopState::Break(Ok(x)), + Err(x) => LoopState::Break(Err(x)), + } + } + + self.try_fold((), check(f)).break_value().transpose() } /// Searches for an element in an iterator, returning its index.