Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Zip::all() #615

Merged
merged 2 commits into from Apr 25, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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.
mneumann marked this conversation as resolved.
Show resolved Hide resolved
/// 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));
mneumann marked this conversation as resolved.
Show resolved Hide resolved
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));
}