Add ivec::zip/unzip

This commit is contained in:
Brian Anderson 2011-07-16 17:35:20 -07:00
parent a52c3e0444
commit 8c4f1652ec
2 changed files with 44 additions and 0 deletions

View File

@ -241,6 +241,32 @@ fn find[T](fn(&T) -> bool f, &T[] v) -> option::t[T] {
ret none[T];
}
fn unzip[T, U](&tup(T, U)[] v) -> tup(T[], U[]) {
auto sz = len[tup(T, U)](v);
if (sz == 0u) {
ret tup(~[], ~[]);
} else {
auto rest = slice[tup(T, U)](v, 1u, sz);
auto tl = unzip[T, U](rest);
auto a = ~[v.(0)._0];
auto b = ~[v.(0)._1];
ret tup(a + tl._0, b + tl._1);
}
}
// FIXME make the lengths being equal a constraint
fn zip[T, U](&T[] v, &U[] u) -> tup(T, U)[] {
auto sz = len[T](v);
assert (sz == len[U](u));
if (sz == 0u) {
ret ~[];
} else {
auto rest = zip[T, U](slice[T](v, 1u, sz), slice[U](u, 1u, sz));
ret ~[tup(v.(0), u.(0))] + rest;
}
}
mod unsafe {
type ivec_repr = rec(mutable uint fill,
mutable uint alloc,

View File

@ -262,6 +262,23 @@ fn test_any_and_all() {
assert (!ivec::all(is_three, ~[ 3u, 3u, 0u, 1u, 2u ]));
}
#[test]
fn test_zip_unzip() {
auto v1 = ~[1, 2, 3];
auto v2 = ~[4, 5, 6];
auto z1 = ivec::zip(v1, v2);
assert tup(1, 4) == z1.(0);
assert tup(2, 5) == z1.(1);
assert tup(3, 6) == z1.(2);
auto u1 = ivec::unzip(z1);
assert tup(1, 4) == tup(u1._0.(0), u1._1.(0));
assert tup(2, 5) == tup(u1._0.(1), u1._1.(1));
assert tup(3, 6) == tup(u1._0.(2), u1._1.(2));
}
fn main() {
test_reserve_and_on_heap();
test_unsafe_ptrs();
@ -291,6 +308,7 @@ fn main() {
test_filter_map();
test_foldl();
test_any_and_all();
test_zip_unzip();
}
// Local Variables: