Skip to content

Commit d2cd1e3

Browse files
committed
---
yaml --- r: 3963 b: refs/heads/master c: 8c4f165 h: refs/heads/master i: 3961: 5d33ed3 3959: fbcdbe0 v: v3
1 parent 588e780 commit d2cd1e3

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

[refs]

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
---
2-
refs/heads/master: a52c3e044457aa34d4054bb2734c53a08c3e5d4a
2+
refs/heads/master: 8c4f1652ec4dc42d6012d01d7cd31a2181eff965

trunk/src/lib/ivec.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,32 @@ fn find[T](fn(&T) -> bool f, &T[] v) -> option::t[T] {
241241
ret none[T];
242242
}
243243

244+
fn unzip[T, U](&tup(T, U)[] v) -> tup(T[], U[]) {
245+
auto sz = len[tup(T, U)](v);
246+
if (sz == 0u) {
247+
ret tup(~[], ~[]);
248+
} else {
249+
auto rest = slice[tup(T, U)](v, 1u, sz);
250+
auto tl = unzip[T, U](rest);
251+
auto a = ~[v.(0)._0];
252+
auto b = ~[v.(0)._1];
253+
ret tup(a + tl._0, b + tl._1);
254+
}
255+
}
256+
257+
258+
// FIXME make the lengths being equal a constraint
259+
fn zip[T, U](&T[] v, &U[] u) -> tup(T, U)[] {
260+
auto sz = len[T](v);
261+
assert (sz == len[U](u));
262+
if (sz == 0u) {
263+
ret ~[];
264+
} else {
265+
auto rest = zip[T, U](slice[T](v, 1u, sz), slice[U](u, 1u, sz));
266+
ret ~[tup(v.(0), u.(0))] + rest;
267+
}
268+
}
269+
244270
mod unsafe {
245271
type ivec_repr = rec(mutable uint fill,
246272
mutable uint alloc,

trunk/src/test/run-pass/lib-ivec.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,23 @@ fn test_any_and_all() {
262262
assert (!ivec::all(is_three, ~[ 3u, 3u, 0u, 1u, 2u ]));
263263
}
264264

265+
#[test]
266+
fn test_zip_unzip() {
267+
auto v1 = ~[1, 2, 3];
268+
auto v2 = ~[4, 5, 6];
269+
auto z1 = ivec::zip(v1, v2);
270+
271+
assert tup(1, 4) == z1.(0);
272+
assert tup(2, 5) == z1.(1);
273+
assert tup(3, 6) == z1.(2);
274+
275+
auto u1 = ivec::unzip(z1);
276+
277+
assert tup(1, 4) == tup(u1._0.(0), u1._1.(0));
278+
assert tup(2, 5) == tup(u1._0.(1), u1._1.(1));
279+
assert tup(3, 6) == tup(u1._0.(2), u1._1.(2));
280+
}
281+
265282
fn main() {
266283
test_reserve_and_on_heap();
267284
test_unsafe_ptrs();
@@ -291,6 +308,7 @@ fn main() {
291308
test_filter_map();
292309
test_foldl();
293310
test_any_and_all();
311+
test_zip_unzip();
294312
}
295313

296314
// Local Variables:

0 commit comments

Comments
 (0)