stdlib: Add vec::init. Returns all but the last element.

Per haskell, to go with head/tail, and last.
This commit is contained in:
Brian Anderson 2011-10-28 22:42:38 -07:00
parent d5415a3973
commit a2377ccf91
2 changed files with 43 additions and 1 deletions

View File

@ -193,10 +193,26 @@ fn tail<T>(v: [mutable? T]) : is_not_empty(v) -> [T] {
ret slice(v, 1u, len(v));
}
// FIXME: This name is sort of confusing next to init_fn, etc
// but this is the name haskell uses for this function,
// along with head/tail/last.
/*
Function: init
Returns all but the last elemnt of a vector
Preconditions:
`v` is not empty
*/
fn init<T>(v: [mutable? T]) -> [T] {
assert len(v) != 0u;
slice(v, 0u, len(v) - 1u)
}
/*
Function: last
Returns the last element of `v`
Returns the last element of a vector
Returns:

View File

@ -5,6 +5,7 @@ import std::vec::*;
import std::option;
import std::option::none;
import std::option::some;
import std::task;
fn square(n: uint) -> uint { ret n * n; }
@ -443,6 +444,31 @@ fn reversed_mut() {
assert (v2[1] == 10);
}
#[test]
fn init() {
let v = vec::init([1, 2, 3]);
assert v == [1, 2];
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "mac")]
#[test]
fn init_empty() {
let r = task::join(
task::spawn_joinable((), fn (&&_i: ()) {
task::unsupervise();
vec::init::<int>([]);
}));
assert r == task::tr_failure
}
// FIXME: Windows can't undwind
#[cfg(target_os = "win32")]
#[test]
#[ignore]
fn init_empty() { }
// Local Variables:
// mode: rust;
// fill-column: 78;