diff --git a/src/zip/mod.rs b/src/zip/mod.rs index b26e2aebb..fc8b99c7d 100644 --- a/src/zip/mod.rs +++ b/src/zip/mod.rs @@ -738,6 +738,32 @@ macro_rules! map_impl { }) } + /// Tests if every element of the iterator matches a predicate. + /// + /// Returns `true` if `predicate` evaluates to `true` for all elements. + /// Returns `true` if the input arrays are empty. + /// + /// Example: + /// + /// ``` + /// use ndarray::{array, Zip}; + /// let a = array![1, 2, 3]; + /// let b = array![1, 4, 9]; + /// assert!(Zip::from(&a).and(&b).all(|&a, &b| a * a == b)); + /// ``` + pub fn all(mut self, mut predicate: F) -> bool + where F: FnMut($($p::Item),*) -> bool + { + self.apply_core(true, move |_, args| { + let ($($p,)*) = args; + if predicate($($p),*) { + FoldWhile::Continue(true) + } else { + FoldWhile::Done(false) + } + }).into_inner() + } + expand_if!(@bool [$notlast] /// Include the producer `p` in the Zip. diff --git a/tests/azip.rs b/tests/azip.rs index a5e53e0e0..39a5d2991 100644 --- a/tests/azip.rs +++ b/tests/azip.rs @@ -271,3 +271,22 @@ fn test_indices_split_1() { } } } + +#[test] +fn test_zip_all() { + let a = Array::::zeros(62); + let b = Array::::ones(62); + let mut c = Array::::ones(62); + c[5] = 0.0; + assert_eq!(true, Zip::from(&a).and(&b).all(|&x, &y| x + y == 1.0)); + assert_eq!(false, Zip::from(&a).and(&b).all(|&x, &y| x == y)); + assert_eq!(false, Zip::from(&a).and(&c).all(|&x, &y| x + y == 1.0)); +} + +#[test] +fn test_zip_all_empty_array() { + let a = Array::::zeros(0); + let b = Array::::ones(0); + assert_eq!(true, Zip::from(&a).and(&b).all(|&_x, &_y| true)); + assert_eq!(true, Zip::from(&a).and(&b).all(|&_x, &_y| false)); +}