Skip to content

Commit

Permalink
Rollup merge of #102435 - GuillaumeGomez:improve-iterator-reduce-exam…
Browse files Browse the repository at this point in the history
…ple, r=thomcc,vacuus

Improve example of Iterator::reduce

Fixes #81819.

I took your example `@bstrie` from #81819 and applied it here.

r? `@thomcc`
  • Loading branch information
Dylan-DPC authored Sep 29, 2022
2 parents 33553e1 + 49b25d3 commit b6d1c15
Showing 1 changed file with 5 additions and 14 deletions.
19 changes: 5 additions & 14 deletions library/core/src/iter/traits/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2431,22 +2431,13 @@ pub trait Iterator {
///
/// # Example
///
/// Find the maximum value:
///
/// ```
/// fn find_max<I>(iter: I) -> Option<I::Item>
/// where I: Iterator,
/// I::Item: Ord,
/// {
/// iter.reduce(|accum, item| {
/// if accum >= item { accum } else { item }
/// })
/// }
/// let a = [10, 20, 5, -23, 0];
/// let b: [u32; 0] = [];
/// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap();
/// assert_eq!(reduced, 45);
///
/// assert_eq!(find_max(a.iter()), Some(&20));
/// assert_eq!(find_max(b.iter()), None);
/// // Which is equivalent to doing it with `fold`:
/// let folded: i32 = (1..10).fold(0, |acc, e| acc + e);
/// assert_eq!(reduced, folded);
/// ```
#[inline]
#[stable(feature = "iterator_fold_self", since = "1.51.0")]
Expand Down

0 comments on commit b6d1c15

Please sign in to comment.