Skip to content

Commit b36f56a

Browse files
committed
Implement Zip::all()
Test if every element of the iterator matches a predicate. This is useful, for instance, to test if two matrices are elementwise "similar" (within a given threshold) without modifying the matrices.
1 parent 2924f2e commit b36f56a

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/zip/mod.rs

+16
Original file line numberDiff line numberDiff line change
@@ -738,6 +738,22 @@ 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+
pub fn all<F>(mut self, mut predicate: F) -> bool
745+
where F: FnMut($($p::Item),*) -> bool
746+
{
747+
self.apply_core(true, move |_, args| {
748+
let ($($p,)*) = args;
749+
if predicate($($p),*) {
750+
FoldWhile::Continue(true)
751+
} else {
752+
FoldWhile::Done(false)
753+
}
754+
}).into_inner()
755+
}
756+
741757
expand_if!(@bool [$notlast]
742758

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

tests/azip.rs

+16
Original file line numberDiff line numberDiff line change
@@ -271,3 +271,19 @@ 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+
assert_eq!(true, Zip::from(&a).and(&b).all(|&x, &y| x + y == 1.0));
280+
assert_eq!(false, Zip::from(&a).and(&b).all(|&x, &y| x == y));
281+
}
282+
283+
#[test]
284+
fn test_zip_all_empty_array() {
285+
let a = Array::<f32, _>::zeros(0);
286+
let b = Array::<f32, _>::ones(0);
287+
assert_eq!(true, Zip::from(&a).and(&b).all(|&_x, &_y| true));
288+
assert_eq!(true, Zip::from(&a).and(&b).all(|&_x, &_y| false));
289+
}

0 commit comments

Comments
 (0)