diff --git a/src/lib/ivec.rs b/src/lib/ivec.rs index 25e1e0118e8..10f5e33505b 100644 --- a/src/lib/ivec.rs +++ b/src/lib/ivec.rs @@ -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; } diff --git a/src/test/run-pass/lib-ivec.rs b/src/test/run-pass/lib-ivec.rs index 528bfc9395f..6de08db33b8 100644 --- a/src/test/run-pass/lib-ivec.rs +++ b/src/test/run-pass/lib-ivec.rs @@ -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();