Skip to content

Commit

Permalink
Add .last() and .last_mut() methods to ArrayBase
Browse files Browse the repository at this point in the history
  • Loading branch information
jturner314 committed May 27, 2021
1 parent e7600e8 commit 516294b
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions src/impl_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,66 @@ where
}
}

/// Returns a reference to the last element of the array, or `None` if it
/// is empty.
///
/// # Example
///
/// ```rust
/// use ndarray::Array3;
///
/// let mut a = Array3::<f64>::zeros([3, 4, 2]);
/// a[[2, 3, 1]] = 42.;
/// assert_eq!(a.last(), Some(&42.));
///
/// let b = Array3::<f64>::zeros([3, 0, 5]);
/// assert_eq!(b.last(), None);
/// ```
pub fn last(&self) -> Option<&A>
where
S: Data,
{
if self.is_empty() {
None
} else {
let mut index = self.raw_dim();
for ax in 0..index.ndim() {
index[ax] -= 1;
}
Some(unsafe { self.uget(index) })
}
}

/// Returns a mutable reference to the last element of the array, or `None`
/// if it is empty.
///
/// # Example
///
/// ```rust
/// use ndarray::Array3;
///
/// let mut a = Array3::<f64>::zeros([3, 4, 2]);
/// *a.last_mut().unwrap() = 42.;
/// assert_eq!(a[[2, 3, 1]], 42.);
///
/// let mut b = Array3::<f64>::zeros([3, 0, 5]);
/// assert_eq!(b.last_mut(), None);
/// ```
pub fn last_mut(&mut self) -> Option<&mut A>
where
S: DataMut,
{
if self.is_empty() {
None
} else {
let mut index = self.raw_dim();
for ax in 0..index.ndim() {
index[ax] -= 1;
}
Some(unsafe { self.uget_mut(index) })
}
}

/// Return an iterator of references to the elements of the array.
///
/// Elements are visited in the *logical order* of the array, which
Expand Down

0 comments on commit 516294b

Please sign in to comment.