diff options
| author | Patrick Walton <[email protected]> | 2010-11-09 15:35:40 -0800 |
|---|---|---|
| committer | Patrick Walton <[email protected]> | 2010-11-09 15:38:42 -0800 |
| commit | 3e482d5f69ffb56f0503e783b50599ec0d873dec (patch) | |
| tree | 0ecf537aee28d13858d193b49cab130d8dbaa892 /src | |
| parent | Support a special const-value refcount, use it for const strings. (diff) | |
| download | rust-3e482d5f69ffb56f0503e783b50599ec0d873dec.tar.xz rust-3e482d5f69ffb56f0503e783b50599ec0d873dec.zip | |
Implement a map2() function in std._vec
Diffstat (limited to 'src')
| -rw-r--r-- | src/lib/_vec.rs | 18 | ||||
| -rw-r--r-- | src/test/run-pass/lib-vec.rs | 19 |
2 files changed, 36 insertions, 1 deletions
diff --git a/src/lib/_vec.rs b/src/lib/_vec.rs index 6fa0ed42..2ffe8bad 100644 --- a/src/lib/_vec.rs +++ b/src/lib/_vec.rs @@ -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; diff --git a/src/test/run-pass/lib-vec.rs b/src/test/run-pass/lib-vec.rs index 815a3aa2..4d616648 100644 --- a/src/test/run-pass/lib-vec.rs +++ b/src/test/run-pass/lib-vec.rs @@ -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(); } + |