Clean up zip and unzip in std::ivec

This commit is contained in:
Marijn Haverbeke 2011-08-15 14:32:58 +02:00
parent dfcf997801
commit 92719e438c
4 changed files with 25 additions and 30 deletions

View File

@ -269,30 +269,25 @@ fn position_pred[T](f: fn(&T) -> bool , v: &[T]) -> option::t[uint] {
ret none[uint];
}
fn unzip[@T, @U](v: &[{_0: T, _1: U}]) -> {_0: [T], _1: [U]} {
let sz = len(v);
if sz == 0u {
ret {_0: ~[], _1: ~[]};
} else {
let rest = slice(v, 1u, sz);
let tl = unzip(rest);
let a = ~[v.(0)._0];
let b = ~[v.(0)._1];
ret {_0: a + tl._0, _1: b + tl._1};
fn unzip[@T, @U](v: &[(T, U)]) -> ([T], [U]) {
let as = ~[], bs = ~[];
for (a, b) in v {
as += ~[a];
bs += ~[b];
}
ret (as, bs);
}
// FIXME make the lengths being equal a constraint
fn zip[@T, @U](v: &[T], u: &[U]) -> [{_0: T, _1: U}] {
let sz = len(v);
fn zip[@T, @U](v: &[T], u: &[U]) -> [(T, U)] {
let zipped = ~[];
let sz = len(v), i = 0u;
assert (sz == len(u));
if sz == 0u {
ret ~[];
} else {
let rest = zip(slice(v, 1u, sz), slice(u, 1u, sz));
ret ~[{_0: v.(0), _1: u.(0)}] + rest;
while i < sz {
zipped += ~[(v.(i), u.(i))];
i += 1u;
}
ret zipped;
}
// Swaps two elements in a vector

View File

@ -314,15 +314,15 @@ fn test_zip_unzip() {
let v2 = ~[4, 5, 6];
let z1 = ivec::zip(v1, v2);
assert ({_0: 1, _1: 4} == z1.(0));
assert ({_0: 2, _1: 5} == z1.(1));
assert ({_0: 3, _1: 6} == z1.(2));
assert ((1, 4) == z1.(0));
assert ((2, 5) == z1.(1));
assert ((3, 6) == z1.(2));
let u1 = ivec::unzip(z1);
let (left, right) = ivec::unzip(z1);
assert ({_0: 1, _1: 4} == {_0: u1._0.(0), _1: u1._1.(0)});
assert ({_0: 2, _1: 5} == {_0: u1._0.(1), _1: u1._1.(1)});
assert ({_0: 3, _1: 6} == {_0: u1._0.(2), _1: u1._1.(2)});
assert ((1, 4) == (left.(0), right.(0)));
assert ((2, 5) == (left.(1), right.(1)));
assert ((3, 6) == (left.(2), right.(2)));
}
#[test]

View File

@ -50,9 +50,9 @@ fn test_simple() {
sort::quick_sort(lteq, names);
let pairs = ivec::zip(expected, ivec::from_mut(names));
for p: {_0: int, _1: int} in pairs {
log #fmt("%d %d", p._0, p._1);
assert (p._0 == p._1);
for (a, b) in pairs {
log #fmt("%d %d", a, b);
assert (a == b);
}
}

View File

@ -89,8 +89,8 @@ fn sort_tests() {
let pairs = ivec::zip(expected, filtered);
for p: {_0: str, _1: test::test_desc} in pairs {
assert (p._0 == p._1.name);
for (a, b) in pairs {
assert (a == b.name);
}
}