Skip to content

Proposal: fold_self and try_fold_self for Iterators #60103

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions src/libcore/iter/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1586,6 +1586,46 @@ pub trait Iterator {
Try::from_ok(accum)
}

/// The same as [`try_fold()`](#method.try_fold), but uses the first element
/// in the iterator as the initial value, folding every subsequent element
/// into it. If the iterator is empty, return None; otherwise, return the
/// result of the fold.
///
/// # Examples
///
/// Find the maximum value:
///
/// ```
/// use std::cmp::Ordering;
/// fn find_max<I>(iter: I) -> Option<I::Item>
/// where I: Iterator,
/// I::Item: PartialCmp,
/// {
/// iter.try_fold_self(|a, b| {
/// a.partial_cmp(b).map(move |cmp| match cmp {
/// Ordering::Greater | Ordering::Equal => a,
/// Ordering::Less => b,
/// })
/// })
/// }
/// let a = [10, 20, 5, -23, 0];
/// let b = [10, 20, -23, std::f64::NAN, 12, 2.5];
/// let c = [];
///
/// assert_eq!(find_max(a.iter()), Some(Some(20)));
/// assert_eq!(find_max(b.iter()), Some(None));
/// assert_eq!(find_max(c.iter()), None);
/// ```
#[inline]
#[unstable(feature = "iterator_fold_self", issue = "60103")]
fn try_fold_self<F, R>(&mut self, mut f: F) -> Option<R>
where Self: Sized,
F: FnMut(Self::Item, Self::Item) -> R,
R: Try<Ok = Self::Item>
{
self.next().map(move |first| self.try_fold(first, f))
}

/// An iterator method that applies a fallible function to each item in the
/// iterator, stopping at the first error and returning that error.
///
Expand Down Expand Up @@ -1696,6 +1736,41 @@ pub trait Iterator {
self.try_fold(init, move |acc, x| Ok::<B, !>(f(acc, x))).unwrap()
}

/// The same as [`fold()`](#method.fold), but uses the first element in the
/// iterator as the initial value, folding every subsequent element into it.
/// If the iterator is empty, return `None`; otherwise, return the result
/// of the fold.
///
/// # Example
///
/// Find the maximum value:
///
/// ```
/// fn find_max<I>(iter: I) -> Option<I::Item>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aside from the behavior for Equal, this is just Iterator::max -- maybe a different example can be provided?

/// where I: Iterator,
/// I::Item: Ord,
/// {
/// iter.fold_self(|a, b| {
/// a.partial_cmp(b).map(move |cmp| match cmp {
/// Ordering::Greater | Ordering::Equal => a,
/// Ordering::Less => b,
/// })
/// })
/// }
/// let a = [10, 20, 5, -23, 0];
/// let b = [];
///
/// assert_eq!(find_max(a.iter()), Some(20));
/// assert_eq!(find_max(b.iter()), None));
/// ```
#[inline]
#[unstable(feature = "iterator_fold_self", issue = "60103")]
fn fold_self<F>(mut self, mut f: F) -> Option<Self::Item>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where Self: Sized, F: FnMut(Self::Item, Self::Item) -> Self::Item
{
self.next().map(move |first| self.fold(first, f))
}

/// Tests if every element of the iterator matches a predicate.
///
/// `all()` takes a closure that returns `true` or `false`. It applies
Expand Down