Skip to content

Commit

Permalink
Merge pull request #615 from mneumann/zip_all
Browse files Browse the repository at this point in the history
Implement Zip::all()
  • Loading branch information
LukeMathWalker committed Apr 25, 2019
2 parents 2b8dcf3 + 48275c4 commit 44bf8b8
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/zip/mod.rs
Expand Up @@ -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<F>(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.
Expand Down
19 changes: 19 additions & 0 deletions tests/azip.rs
Expand Up @@ -271,3 +271,22 @@ fn test_indices_split_1() {
}
}
}

#[test]
fn test_zip_all() {
let a = Array::<f32, _>::zeros(62);
let b = Array::<f32, _>::ones(62);
let mut c = Array::<f32, _>::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::<f32, _>::zeros(0);
let b = Array::<f32, _>::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));
}

0 comments on commit 44bf8b8

Please sign in to comment.