Skip to content

Commit 44bf8b8

Browse files
Merge pull request #615 from mneumann/zip_all
Implement Zip::all()
2 parents 2b8dcf3 + 48275c4 commit 44bf8b8

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/zip/mod.rs

+26
Original file line numberDiff line numberDiff line change
@@ -738,6 +738,32 @@ macro_rules! map_impl {
738738
})
739739
}
740740

741+
/// Tests if every element of the iterator matches a predicate.
742+
///
743+
/// Returns `true` if `predicate` evaluates to `true` for all elements.
744+
/// Returns `true` if the input arrays are empty.
745+
///
746+
/// Example:
747+
///
748+
/// ```
749+
/// use ndarray::{array, Zip};
750+
/// let a = array![1, 2, 3];
751+
/// let b = array![1, 4, 9];
752+
/// assert!(Zip::from(&a).and(&b).all(|&a, &b| a * a == b));
753+
/// ```
754+
pub fn all<F>(mut self, mut predicate: F) -> bool
755+
where F: FnMut($($p::Item),*) -> bool
756+
{
757+
self.apply_core(true, move |_, args| {
758+
let ($($p,)*) = args;
759+
if predicate($($p),*) {
760+
FoldWhile::Continue(true)
761+
} else {
762+
FoldWhile::Done(false)
763+
}
764+
}).into_inner()
765+
}
766+
741767
expand_if!(@bool [$notlast]
742768

743769
/// Include the producer `p` in the Zip.

tests/azip.rs

+19
Original file line numberDiff line numberDiff line change
@@ -271,3 +271,22 @@ fn test_indices_split_1() {
271271
}
272272
}
273273
}
274+
275+
#[test]
276+
fn test_zip_all() {
277+
let a = Array::<f32, _>::zeros(62);
278+
let b = Array::<f32, _>::ones(62);
279+
let mut c = Array::<f32, _>::ones(62);
280+
c[5] = 0.0;
281+
assert_eq!(true, Zip::from(&a).and(&b).all(|&x, &y| x + y == 1.0));
282+
assert_eq!(false, Zip::from(&a).and(&b).all(|&x, &y| x == y));
283+
assert_eq!(false, Zip::from(&a).and(&c).all(|&x, &y| x + y == 1.0));
284+
}
285+
286+
#[test]
287+
fn test_zip_all_empty_array() {
288+
let a = Array::<f32, _>::zeros(0);
289+
let b = Array::<f32, _>::ones(0);
290+
assert_eq!(true, Zip::from(&a).and(&b).all(|&_x, &_y| true));
291+
assert_eq!(true, Zip::from(&a).and(&b).all(|&_x, &_y| false));
292+
}

0 commit comments

Comments
 (0)