Skip to content

Commit 70effa7

Browse files
authored
Merge pull request #420 from jturner314/neg-step-slice-docs
Add documentation for slicing with negative step
2 parents b32663d + 094fc31 commit 70effa7

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/slice.rs

+35
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ use super::Dimension;
1616
/// Negative `begin` or `end` indexes are counted from the back of the axis. If
1717
/// `end` is `None`, the slice extends to the end of the axis.
1818
///
19+
/// See also the [`s![]`](macro.s.html) macro.
20+
///
1921
/// ## Examples
2022
///
2123
/// `Slice::new(0, None, 1)` is the full range of an axis. It can also be
@@ -531,6 +533,39 @@ impl<D1: Dimension> SliceNextDim<D1, D1::Larger> for RangeFull {
531533
/// }
532534
/// # fn main() { }
533535
/// ```
536+
///
537+
/// # Negative *step*
538+
///
539+
/// The behavior of negative *step* arguments is most easily understood with
540+
/// slicing as a two-step process:
541+
///
542+
/// 1. First, perform a slice with *range*.
543+
///
544+
/// 2. If *step* is positive, start with the front of the slice; if *step* is
545+
/// negative, start with the back of the slice. Then, add *step* until
546+
/// reaching the other end of the slice (inclusive).
547+
///
548+
/// An equivalent way to think about step 2 is, "If *step* is negative, reverse
549+
/// the slice. Start at the front of the (possibly reversed) slice, and add
550+
/// *step.abs()* until reaching the back of the slice (inclusive)."
551+
///
552+
/// For example,
553+
///
554+
/// ```
555+
/// # #[macro_use]
556+
/// # extern crate ndarray;
557+
/// #
558+
/// # use ndarray::prelude::*;
559+
/// #
560+
/// # fn main() {
561+
/// let arr = array![0, 1, 2, 3];
562+
/// assert_eq!(arr.slice(s![1..3;-1]), array![2, 1]);
563+
/// assert_eq!(arr.slice(s![1..;-2]), array![3, 1]);
564+
/// assert_eq!(arr.slice(s![0..4;-2]), array![3, 1]);
565+
/// assert_eq!(arr.slice(s![0..;-2]), array![3, 1]);
566+
/// assert_eq!(arr.slice(s![..;-2]), array![3, 1]);
567+
/// # }
568+
/// ```
534569
#[macro_export]
535570
macro_rules! s(
536571
// convert a..b;c into @convert(a..b, c), final item

0 commit comments

Comments
 (0)