From a2377ccf91158ce5c9da2e5d0cc1f56fa562b2fe Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 28 Oct 2011 22:42:38 -0700 Subject: [PATCH] stdlib: Add vec::init. Returns all but the last element. Per haskell, to go with head/tail, and last. --- src/lib/vec.rs | 18 +++++++++++++++++- src/test/stdtest/vec.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/lib/vec.rs b/src/lib/vec.rs index a378b8ff2d4..548afaa73bc 100644 --- a/src/lib/vec.rs +++ b/src/lib/vec.rs @@ -193,10 +193,26 @@ fn tail(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(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: diff --git a/src/test/stdtest/vec.rs b/src/test/stdtest/vec.rs index 453c9f8e414..5f644c450b6 100644 --- a/src/test/stdtest/vec.rs +++ b/src/test/stdtest/vec.rs @@ -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::([]); + })); + 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;