Skip to content

Commit 26af55f

Browse files
committed
Improve documentation of Iterator::{fold, reduce}.
1 parent 5c056ed commit 26af55f

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

library/core/src/iter/traits/iterator.rs

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2028,7 +2028,8 @@ pub trait Iterator {
20282028
self.try_fold((), call(f))
20292029
}
20302030

2031-
/// An iterator method that applies a function, producing a single, final value.
2031+
/// Folds every element into an accumulator by applying an operation,
2032+
/// returning the final result.
20322033
///
20332034
/// `fold()` takes two arguments: an initial value, and a closure with two
20342035
/// arguments: an 'accumulator', and an element. The closure returns the value that
@@ -2049,6 +2050,9 @@ pub trait Iterator {
20492050
/// may not terminate for infinite iterators, even on traits for which a
20502051
/// result is determinable in finite time.
20512052
///
2053+
/// Note: [`reduce()`] can be used to use the first element as the initial
2054+
/// value, if the accumulator type and item type is the same.
2055+
///
20522056
/// # Note to Implementors
20532057
///
20542058
/// Several of the other (forward) methods have default implementations in
@@ -2104,6 +2108,8 @@ pub trait Iterator {
21042108
/// // they're the same
21052109
/// assert_eq!(result, result2);
21062110
/// ```
2111+
///
2112+
/// [`reduce()`]: Iterator::reduce
21072113
#[doc(alias = "reduce")]
21082114
#[doc(alias = "inject")]
21092115
#[inline]
@@ -2120,10 +2126,15 @@ pub trait Iterator {
21202126
accum
21212127
}
21222128

2123-
/// The same as [`fold()`], but uses the first element in the
2124-
/// iterator as the initial value, folding every subsequent element into it.
2125-
/// If the iterator is empty, return [`None`]; otherwise, return the result
2126-
/// of the fold.
2129+
/// Reduces the elements to a single one, by repeatedly applying a reducing
2130+
/// operation.
2131+
///
2132+
/// If the iterator is empty, returns [`None`]; otherwise, returns the
2133+
/// result of the reduction.
2134+
///
2135+
/// For iterators with at least one element, this is the same as [`fold()`]
2136+
/// with the first element of the iterator as the initial value, folding
2137+
/// every subsequent element into it.
21272138
///
21282139
/// [`fold()`]: Iterator::fold
21292140
///

0 commit comments

Comments
 (0)