Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added two version of reverse and a swap function to the standard library. #396

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/lib/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,45 @@ fn freeze[T](vec[mutable T] v) -> vec[T] {
ret result;
}

// Swaps two elements in a vector
fn swap[T](&vec[T] v, uint a, uint b) {
let T t = v.(a);
v.(a) = v.(b);
v.(b) = t;
}

// In place vector reversal
fn reverse[T](&vec[T] v) -> () {
let uint i = 0u;
auto ln = len[T](v);

while(i < ln / 2u) {
swap(v, i, ln - i - 1u);
i += 1u;
}
}

// Functional vector reversal. Returns a reversed copy of v.
fn reversed[T](vec[T] v) -> vec[T] {
let vec[T] res = [];

auto i = len[T](v);
if (i == 0u) {
ret res;
}
else {
i -= 1u;
}

while(i != 0u) {
push[T](res, v.(i));
i -= 1u;
}
push[T](res, v.(0));

ret res;
}

// Local Variables:
// mode: rust;
// fill-column: 78;
Expand Down
29 changes: 29 additions & 0 deletions src/test/run-pass/vec-reverse.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use std;
import std::vec;

fn main() {
let vec[int] v = [10, 20];

assert v.(0) == 10;
assert v.(1) == 20;

vec::reverse[int](v);

assert v.(0) == 20;
assert v.(1) == 10;

auto v2 = vec::reversed[int](v);

assert v2.(0) == 10;
assert v2.(1) == 20;

v.(0) = 30;

assert v2.(0) == 10;

// Make sure they work with 0-length vectors too.
let vec[int] v3 = [];
auto v4 = vec::reversed[int](v3);

vec::reverse[int](v3);
}