Implement a map2() function in std._vec

This commit is contained in:
Patrick Walton 2010-11-09 15:35:40 -08:00
parent 89946609f2
commit 3e482d5f69
2 changed files with 36 additions and 1 deletions

View File

@ -1,6 +1,8 @@
import vbuf = rustrt.vbuf;
import std.option;
type operator2[T,U,V] = fn(&T, &U) -> V;
native "rust" mod rustrt {
type vbuf;
@ -142,6 +144,22 @@ fn map[T, U](&option.operator[T,U] f, &vec[T] v) -> vec[U] {
ret u;
}
fn map2[T,U,V](&operator2[T,U,V] f, &vec[T] v0, &vec[U] v1) -> vec[V] {
auto v0_len = len[T](v0);
if (v0_len != len[U](v1)) {
fail;
}
let vec[V] u = alloc[V](v0_len);
auto i = 0u;
while (i < v0_len) {
u += f(v0.(i), v1.(i));
i += 1u;
}
ret u;
}
// Local Variables:
// mode: rust;
// fill-column: 78;

View File

@ -37,7 +37,21 @@ fn test_map() {
let vec[int] s = std._vec.map[int, int](op, v);
let int i = 0;
while (i < 5) {
check (v.(i) == s.(i));
check (v.(i) * v.(i) == s.(i));
i += 1;
}
}
fn test_map2() {
fn times(&int x, &int y) -> int { ret x * y; }
auto f = times;
auto v0 = vec(1, 2, 3, 4, 5);
auto v1 = vec(5, 4, 3, 2, 1);
auto u = std._vec.map2[int,int,int](f, v0, v1);
auto i = 0;
while (i < 5) {
check (v0.(i) * v1.(i) == u.(i));
i += 1;
}
}
@ -46,4 +60,7 @@ fn main() {
test_init_elt();
test_init_fn();
test_slice();
test_map();
test_map2();
}