libcore: Add vec any2 and all2 functions.

This commit is contained in:
Erick Tryzelaar
2011-12-19 09:46:09 -08:00
parent f9df32adac
commit 6b1c60d312
2 changed files with 49 additions and 0 deletions

View File

@@ -507,6 +507,24 @@ fn any<T>(v: [T], f: block(T) -> bool) -> bool {
ret false;
}
/*
Function: any2
Return true if a predicate matches any elements in both vectors.
If the vectors contains no elements then false is returned.
*/
fn any2<T, U>(v0: [T], v1: [U], f: block(T, U) -> bool) -> bool {
let v0_len = len(v0);
let v1_len = len(v1);
let i = 0u;
while i < v0_len && i < v1_len {
if f(v0[i], v1[i]) { ret true; };
i += 1u;
}
ret false;
}
/*
Function: all
@@ -519,6 +537,21 @@ fn all<T>(v: [T], f: block(T) -> bool) -> bool {
ret true;
}
/*
Function: all2
Return true if a predicate matches all elements in both vectors.
If the vectors are not the same size then false is returned.
*/
fn all2<T, U>(v0: [T], v1: [U], f: block(T, U) -> bool) -> bool {
let v0_len = len(v0);
if v0_len != len(v1) { ret false; }
let i = 0u;
while i < v0_len { if !f(v0[i], v1[i]) { ret false; }; i += 1u; }
ret true;
}
/*
Function: member

View File

@@ -16,6 +16,8 @@ pure fn is_three(&&n: uint) -> bool { ret n == 3u; }
pure fn is_odd(&&n: uint) -> bool { ret n % 2u == 1u; }
pure fn is_equal(&&x: uint, &&y:uint) -> bool { ret x == y; }
fn square_if_odd(&&n: uint) -> option::t<uint> {
ret if n % 2u == 1u { some(n * n) } else { none };
}
@@ -401,6 +403,20 @@ fn test_any_and_all() {
assert (!vec::all([3u, 3u, 0u, 1u, 2u], is_three));
}
#[test]
fn test_any2_and_all2() {
assert (vec::any2([2u, 4u, 6u], [2u, 4u, 6u], is_equal));
assert (vec::any2([1u, 2u, 3u], [4u, 5u, 3u], is_equal));
assert (!vec::any2([1u, 2u, 3u], [4u, 5u, 6u], is_equal));
assert (vec::any2([2u, 4u, 6u], [2u, 4u], is_equal));
assert (vec::all2([2u, 4u, 6u], [2u, 4u, 6u], is_equal));
assert (!vec::all2([1u, 2u, 3u], [4u, 5u, 3u], is_equal));
assert (!vec::all2([1u, 2u, 3u], [4u, 5u, 6u], is_equal));
assert (!vec::all2([2u, 4u, 6u], [2u, 4u], is_equal));
}
#[test]
fn test_zip_unzip() {
let v1 = [1, 2, 3];