Skip to content

Commit 6b1c60d

Browse files
committed
libcore: Add vec any2 and all2 functions.
1 parent f9df32a commit 6b1c60d

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/libcore/vec.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -507,6 +507,24 @@ fn any<T>(v: [T], f: block(T) -> bool) -> bool {
507507
ret false;
508508
}
509509

510+
/*
511+
Function: any2
512+
513+
Return true if a predicate matches any elements in both vectors.
514+
515+
If the vectors contains no elements then false is returned.
516+
*/
517+
fn any2<T, U>(v0: [T], v1: [U], f: block(T, U) -> bool) -> bool {
518+
let v0_len = len(v0);
519+
let v1_len = len(v1);
520+
let i = 0u;
521+
while i < v0_len && i < v1_len {
522+
if f(v0[i], v1[i]) { ret true; };
523+
i += 1u;
524+
}
525+
ret false;
526+
}
527+
510528
/*
511529
Function: all
512530
@@ -519,6 +537,21 @@ fn all<T>(v: [T], f: block(T) -> bool) -> bool {
519537
ret true;
520538
}
521539

540+
/*
541+
Function: all2
542+
543+
Return true if a predicate matches all elements in both vectors.
544+
545+
If the vectors are not the same size then false is returned.
546+
*/
547+
fn all2<T, U>(v0: [T], v1: [U], f: block(T, U) -> bool) -> bool {
548+
let v0_len = len(v0);
549+
if v0_len != len(v1) { ret false; }
550+
let i = 0u;
551+
while i < v0_len { if !f(v0[i], v1[i]) { ret false; }; i += 1u; }
552+
ret true;
553+
}
554+
522555
/*
523556
Function: member
524557

src/test/stdtest/vec.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ pure fn is_three(&&n: uint) -> bool { ret n == 3u; }
1616

1717
pure fn is_odd(&&n: uint) -> bool { ret n % 2u == 1u; }
1818

19+
pure fn is_equal(&&x: uint, &&y:uint) -> bool { ret x == y; }
20+
1921
fn square_if_odd(&&n: uint) -> option::t<uint> {
2022
ret if n % 2u == 1u { some(n * n) } else { none };
2123
}
@@ -401,6 +403,20 @@ fn test_any_and_all() {
401403
assert (!vec::all([3u, 3u, 0u, 1u, 2u], is_three));
402404
}
403405

406+
#[test]
407+
fn test_any2_and_all2() {
408+
409+
assert (vec::any2([2u, 4u, 6u], [2u, 4u, 6u], is_equal));
410+
assert (vec::any2([1u, 2u, 3u], [4u, 5u, 3u], is_equal));
411+
assert (!vec::any2([1u, 2u, 3u], [4u, 5u, 6u], is_equal));
412+
assert (vec::any2([2u, 4u, 6u], [2u, 4u], is_equal));
413+
414+
assert (vec::all2([2u, 4u, 6u], [2u, 4u, 6u], is_equal));
415+
assert (!vec::all2([1u, 2u, 3u], [4u, 5u, 3u], is_equal));
416+
assert (!vec::all2([1u, 2u, 3u], [4u, 5u, 6u], is_equal));
417+
assert (!vec::all2([2u, 4u, 6u], [2u, 4u], is_equal));
418+
}
419+
404420
#[test]
405421
fn test_zip_unzip() {
406422
let v1 = [1, 2, 3];

0 commit comments

Comments
 (0)