@@ -2083,6 +2083,11 @@ pub trait Iterator {
2083
2083
/// Note: [`reduce()`] can be used to use the first element as the initial
2084
2084
/// value, if the accumulator type and item type is the same.
2085
2085
///
2086
+ /// Note: `fold()` combines elements in a *left-associative* fashion. For associative
2087
+ /// operators like `+`, the order the elements are combined in is not important, but for non-associative
2088
+ /// operators like `-` the order will affect the final result.
2089
+ /// For a *right-associative* version of `fold()`, see [`DoubleEndedIterator::rfold()`].
2090
+ ///
2086
2091
/// # Note to Implementors
2087
2092
///
2088
2093
/// Several of the other (forward) methods have default implementations in
@@ -2116,6 +2121,21 @@ pub trait Iterator {
2116
2121
///
2117
2122
/// And so, our final result, `6`.
2118
2123
///
2124
+ /// This example demonstrates the left-associative nature of `fold()`:
2125
+ /// it builds a string, starting with an initial value
2126
+ /// and continuing with each element from the front until the back:
2127
+ ///
2128
+ /// ```
2129
+ /// let numbers = [1, 2, 3, 4, 5];
2130
+ ///
2131
+ /// let zero = "0".to_string();
2132
+ ///
2133
+ /// let result = numbers.iter().fold(zero, |acc, &x| {
2134
+ /// format!("({} + {})", acc, x)
2135
+ /// });
2136
+ ///
2137
+ /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
2138
+ /// ```
2119
2139
/// It's common for people who haven't used iterators a lot to
2120
2140
/// use a `for` loop with a list of things to build up a result. Those
2121
2141
/// can be turned into `fold()`s:
@@ -2140,7 +2160,7 @@ pub trait Iterator {
2140
2160
/// ```
2141
2161
///
2142
2162
/// [`reduce()`]: Iterator::reduce
2143
- #[ doc( alias = "inject" ) ]
2163
+ #[ doc( alias = "inject" , alias = "foldl" ) ]
2144
2164
#[ inline]
2145
2165
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
2146
2166
fn fold < B , F > ( mut self , init : B , mut f : F ) -> B
0 commit comments