stdlib: Add ivec::any() and ivec::all(); put out burning tinderbox

This commit is contained in:
Patrick Walton
2011-07-04 23:52:47 -07:00
parent f71c8dd918
commit 001397da3c
2 changed files with 29 additions and 2 deletions

View File

@@ -171,6 +171,16 @@ fn map[T,U](fn(&T)->U f, &mutable T[mutable?] v) -> U[] {
ret result; ret result;
} }
fn any[T](fn(&T)->bool f, &T[] v) -> bool {
for (T elem in v) { if (f(elem)) { ret true; } }
ret false;
}
fn all[T](fn(&T)->bool f, &T[] v) -> bool {
for (T elem in v) { if (!f(elem)) { ret false; } }
ret true;
}
mod unsafe { mod unsafe {
fn copy_from_buf[T](&mutable T[] v, *T ptr, uint count) { fn copy_from_buf[T](&mutable T[] v, *T ptr, uint count) {

View File

@@ -7,6 +7,10 @@ import std::option::some;
fn square(uint n) -> uint { ret n * n; } fn square(uint n) -> uint { ret n * n; }
fn square_alias(&uint n) -> uint { ret n * n; }
pred is_three(&uint n) -> bool { ret n == 3u; }
fn test_reserve_and_on_heap() { fn test_reserve_and_on_heap() {
let int[] v = ~[ 1, 2 ]; let int[] v = ~[ 1, 2 ];
assert (!ivec::on_heap(v)); assert (!ivec::on_heap(v));
@@ -167,7 +171,7 @@ fn test_grow_set() {
fn test_map() { fn test_map() {
// Test on-stack map. // Test on-stack map.
auto v = ~[ 1u, 2u, 3u ]; auto v = ~[ 1u, 2u, 3u ];
auto w = ivec::map(square, v); auto w = ivec::map(square_alias, v);
assert (ivec::len(w) == 3u); assert (ivec::len(w) == 3u);
assert (w.(0) == 1u); assert (w.(0) == 1u);
assert (w.(1) == 4u); assert (w.(1) == 4u);
@@ -175,7 +179,7 @@ fn test_map() {
// Test on-heap map. // Test on-heap map.
v = ~[ 1u, 2u, 3u, 4u, 5u ]; v = ~[ 1u, 2u, 3u, 4u, 5u ];
w = ivec::map(square, v); w = ivec::map(square_alias, v);
assert (ivec::len(w) == 5u); assert (ivec::len(w) == 5u);
assert (w.(0) == 1u); assert (w.(0) == 1u);
assert (w.(1) == 4u); assert (w.(1) == 4u);
@@ -184,6 +188,18 @@ fn test_map() {
assert (w.(4) == 25u); assert (w.(4) == 25u);
} }
fn test_any_and_all() {
assert (ivec::any(is_three, ~[ 1u, 2u, 3u ]));
assert (!ivec::any(is_three, ~[ 0u, 1u, 2u ]));
assert (ivec::any(is_three, ~[ 1u, 2u, 3u, 4u, 5u ]));
assert (!ivec::any(is_three, ~[ 1u, 2u, 4u, 5u, 6u ]));
assert (ivec::all(is_three, ~[ 3u, 3u, 3u ]));
assert (!ivec::all(is_three, ~[ 3u, 3u, 2u ]));
assert (ivec::all(is_three, ~[ 3u, 3u, 3u, 3u, 3u ]));
assert (!ivec::all(is_three, ~[ 3u, 3u, 0u, 1u, 2u ]));
}
fn main() { fn main() {
test_reserve_and_on_heap(); test_reserve_and_on_heap();
test_unsafe_ptrs(); test_unsafe_ptrs();
@@ -204,5 +220,6 @@ fn main() {
// Functional utilities // Functional utilities
test_map(); test_map();
test_any_and_all();
} }