@@ -2231,4 +2231,60 @@ where
22312231 } )
22322232 }
22332233 }
2234+
2235+ /// Iterates over pairs of consecutive elements along the axis.
2236+ ///
2237+ /// The first argument to the closure is an element, and the second
2238+ /// argument is the next element along the axis. Iteration is guaranteed to
2239+ /// proceed in order along the specified axis, but in all other respects
2240+ /// the iteration order is unspecified.
2241+ ///
2242+ /// # Example
2243+ ///
2244+ /// For example, this can be used to compute the cumulative sum along an
2245+ /// axis:
2246+ ///
2247+ /// ```
2248+ /// use ndarray::{array, Axis};
2249+ ///
2250+ /// let mut arr = array![
2251+ /// [[1, 2], [3, 4], [5, 6]],
2252+ /// [[7, 8], [9, 10], [11, 12]],
2253+ /// ];
2254+ /// arr.accumulate_axis_inplace(Axis(1), |&prev, curr| *curr += prev);
2255+ /// assert_eq!(
2256+ /// arr,
2257+ /// array![
2258+ /// [[1, 2], [4, 6], [9, 12]],
2259+ /// [[7, 8], [16, 18], [27, 30]],
2260+ /// ],
2261+ /// );
2262+ /// ```
2263+ pub fn accumulate_axis_inplace < F > ( & mut self , axis : Axis , mut f : F )
2264+ where
2265+ F : FnMut ( & A , & mut A ) ,
2266+ S : DataMut ,
2267+ {
2268+ if self . len_of ( axis) <= 1 {
2269+ return ;
2270+ }
2271+ let mut prev = self . raw_view ( ) ;
2272+ prev. slice_axis_inplace ( axis, Slice :: from ( ..-1 ) ) ;
2273+ let mut curr = self . raw_view_mut ( ) ;
2274+ curr. slice_axis_inplace ( axis, Slice :: from ( 1 ..) ) ;
2275+ // This implementation relies on `Zip` iterating along `axis` in order.
2276+ Zip :: from ( prev) . and ( curr) . apply ( |prev, curr| unsafe {
2277+ // These pointer dereferences and borrows are safe because:
2278+ //
2279+ // 1. They're pointers to elements in the array.
2280+ //
2281+ // 2. `S: DataMut` guarantees that elements are safe to borrow
2282+ // mutably and that they don't alias.
2283+ //
2284+ // 3. The lifetimes of the borrows last only for the duration
2285+ // of the call to `f`, so aliasing across calls to `f`
2286+ // cannot occur.
2287+ f ( & * prev, & mut * curr)
2288+ } ) ;
2289+ }
22342290}
0 commit comments