Skip to content

Commit 81acf69

Browse files
committed
Add head and tail functions to std::ivec
They even have typestate preconditions
1 parent 139aaa1 commit 81acf69

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/lib/ivec.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,16 @@ pred is_not_empty[T](&T[mutable?] v) -> bool {
8787

8888
// Accessors
8989

90+
/// Returns the first element of a vector
91+
fn head[T](&T[mutable?] v) : is_not_empty(v) -> T {
92+
ret v.(0);
93+
}
94+
95+
/// Returns all but the first element of a vector
96+
fn tail[T](&T[mutable?] v) : is_not_empty(v) -> T[mutable?] {
97+
ret slice(v, 1u, len(v));
98+
}
99+
90100
/// Returns the last element of `v`.
91101
fn last[T](&T[mutable?] v) -> option::t[T] {
92102
if (len(v) == 0u) { ret none; }

src/test/run-pass/lib-ivec.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,22 @@ fn test_is_not_empty() {
9494
assert !ivec::is_not_empty[int](~[]);
9595
}
9696

97+
fn test_head() {
98+
auto a = ~[11, 12];
99+
check ivec::is_not_empty(a);
100+
assert ivec::head(a) == 11;
101+
}
102+
103+
fn test_tail() {
104+
auto a = ~[11];
105+
check ivec::is_not_empty(a);
106+
assert ivec::tail(a) == ~[];
107+
108+
a = ~[11, 12];
109+
check ivec::is_not_empty(a);
110+
assert ivec::tail(a) == ~[12];
111+
}
112+
97113
fn test_last() {
98114
auto n = ivec::last(~[]);
99115
assert (n == none);
@@ -257,6 +273,8 @@ fn main() {
257273
// Accessors
258274
test_init_fn();
259275
test_init_elt();
276+
test_head();
277+
test_tail();
260278
test_last();
261279
test_slice();
262280

0 commit comments

Comments
 (0)