Skip to content

Commit 3122d80

Browse files
committed
libcore: Add IteratorUtil::all, any method
1 parent 54fbac5 commit 3122d80

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/libcore/iterator.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ pub trait IteratorUtil<A> {
5353
fn last(&mut self) -> A;
5454
fn fold<B>(&mut self, start: B, f: &fn(B, A) -> B) -> B;
5555
fn count(&mut self) -> uint;
56+
fn all(&mut self, f: &fn(&A) -> bool) -> bool;
57+
fn any(&mut self, f: &fn(&A) -> bool) -> bool;
5658
}
5759

5860
/// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also
@@ -204,6 +206,18 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
204206
/// Count the number of an iterator elemenrs
205207
#[inline(always)]
206208
fn count(&mut self) -> uint { self.fold(0, |cnt, _x| cnt + 1) }
209+
210+
#[inline(always)]
211+
fn all(&mut self, f: &fn(&A) -> bool) -> bool {
212+
for self.advance |x| { if !f(&x) { return false; } }
213+
return true;
214+
}
215+
216+
#[inline(always)]
217+
fn any(&mut self, f: &fn(&A) -> bool) -> bool {
218+
for self.advance |x| { if f(&x) { return true; } }
219+
return false;
220+
}
207221
}
208222

209223
pub trait AdditiveIterator<A> {
@@ -754,4 +768,21 @@ mod tests {
754768
assert_eq!(v.slice(0, 0).iter().transform(|&x| x).min(), None);
755769
}
756770

771+
#[test]
772+
fn test_all() {
773+
let v = ~&[1, 2, 3, 4, 5];
774+
assert!(v.iter().all(|&x| *x < 10));
775+
assert!(!v.iter().all(|&x| x.is_even()));
776+
assert!(!v.iter().all(|&x| *x > 100));
777+
assert!(v.slice(0, 0).iter().all(|_| fail!()));
778+
}
779+
780+
#[test]
781+
fn test_any() {
782+
let v = ~&[1, 2, 3, 4, 5];
783+
assert!(v.iter().any(|&x| *x < 10));
784+
assert!(v.iter().any(|&x| x.is_even()));
785+
assert!(!v.iter().any(|&x| *x > 100));
786+
assert!(!v.slice(0, 0).iter().any(|_| fail!()));
787+
}
757788
}

0 commit comments

Comments
 (0)