Add head and tail functions to std::ivec

They even have typestate preconditions
This commit is contained in:
Brian Anderson 2011-07-14 15:40:43 -07:00
parent 139aaa1616
commit 81acf69f97
2 changed files with 28 additions and 0 deletions

View File

@ -87,6 +87,16 @@ pred is_not_empty[T](&T[mutable?] v) -> bool {
// Accessors
/// Returns the first element of a vector
fn head[T](&T[mutable?] v) : is_not_empty(v) -> T {
ret v.(0);
}
/// Returns all but the first element of a vector
fn tail[T](&T[mutable?] v) : is_not_empty(v) -> T[mutable?] {
ret slice(v, 1u, len(v));
}
/// Returns the last element of `v`.
fn last[T](&T[mutable?] v) -> option::t[T] {
if (len(v) == 0u) { ret none; }

View File

@ -94,6 +94,22 @@ fn test_is_not_empty() {
assert !ivec::is_not_empty[int](~[]);
}
fn test_head() {
auto a = ~[11, 12];
check ivec::is_not_empty(a);
assert ivec::head(a) == 11;
}
fn test_tail() {
auto a = ~[11];
check ivec::is_not_empty(a);
assert ivec::tail(a) == ~[];
a = ~[11, 12];
check ivec::is_not_empty(a);
assert ivec::tail(a) == ~[12];
}
fn test_last() {
auto n = ivec::last(~[]);
assert (n == none);
@ -257,6 +273,8 @@ fn main() {
// Accessors
test_init_fn();
test_init_elt();
test_head();
test_tail();
test_last();
test_slice();