about summary refs log tree commit diff
diff options
context:
space:
mode:
authorBrian Anderson <banderson@mozilla.com>2011-07-14 15:40:43 -0700
committerBrian Anderson <banderson@mozilla.com>2011-07-14 17:13:12 -0700
commit81acf69f9708a236ef78faa180575ae7b618fba9 (patch)
tree273c0d9b4daa9ffc91de1bf3ad5e8e060870bd12
parent139aaa1616fd341a71f0f11adb4e8850639e228c (diff)
Add head and tail functions to std::ivec
They even have typestate preconditions
-rw-r--r--src/lib/ivec.rs10
-rw-r--r--src/test/run-pass/lib-ivec.rs18
2 files changed, 28 insertions, 0 deletions
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();