Implement + for @-vectors.

This commit is contained in:
Michael Sullivan 2012-08-08 14:30:30 -07:00
parent f110e8f21c
commit 79b5f68176
2 changed files with 34 additions and 3 deletions

View File

@ -78,6 +78,16 @@ fn vec_reserve_shared_actual(++t: *sys::type_desc,
build_sized(4, builder)
}
// Appending
#[inline(always)]
pure fn append<T: copy>(lhs: @[T], rhs: &[const T]) -> @[T] {
do build_sized(lhs.len() + rhs.len()) |push| {
for vec::each(lhs) |x| { push(x); }
for uint::range(0, rhs.len()) |i| { push(rhs[i]); }
}
}
/// Apply a function to each element of a vector and return the results
pure fn map<T, U>(v: &[T], f: fn(T) -> U) -> @[U] {
do build_sized(v.len()) |push| {
@ -113,6 +123,21 @@ fn vec_reserve_shared_actual(++t: *sys::type_desc,
}
}
impl extensions<T: copy> of vec_concat<T> for @[T] {
#[inline(always)]
pure fn +(rhs: &[const T]) -> @[T] {
append(self, rhs)
}
}
#[cfg(notest)]
impl extensions<T: copy> of add<&[const T],@[T]> for @[T] {
#[inline(always)]
pure fn add(rhs: &[const T]) -> @[T] {
append(self, rhs)
}
}
mod unsafe {
type vec_repr = vec::unsafe::vec_repr;
@ -213,4 +238,10 @@ fn seq_range(lo: uint, hi: uint) -> @[uint] {
assert seq_range(10, 15) == @[10, 11, 12, 13, 14];
assert from_fn(5, |x| x+1) == @[1, 2, 3, 4, 5];
assert from_elem(5, 3.14) == @[3.14, 3.14, 3.14, 3.14, 3.14];
}
}
#[test]
fn append_test() {
assert @[1,2,3] + @[4,5,6] == @[1,2,3,4,5,6];
}

View File

@ -1211,7 +1211,7 @@ fn iter2<U, T>(v1: &[U], v2: &[T], f: fn(U, T)) {
* The total number of permutations produced is `len(v)!`. If `v` contains
* repeated elements, then some permutations are repeated.
*/
pure fn permute<T: copy>(v: &[T], put: fn(~[T])) {
pure fn permute<T: copy>(v: &[const T], put: fn(~[T])) {
let ln = len(v);
if ln == 0u {
put(~[]);
@ -1221,7 +1221,7 @@ fn iter2<U, T>(v1: &[U], v2: &[T], f: fn(U, T)) {
let elt = v[i];
let mut rest = slice(v, 0u, i);
unchecked {
push_all(rest, view(v, i+1u, ln));
push_all(rest, const_view(v, i+1u, ln));
permute(rest, |permutation| {
put(append(~[elt], permutation))
})