Skip to content

Commit a2377cc

Browse files
committed
stdlib: Add vec::init. Returns all but the last element.
Per haskell, to go with head/tail, and last.
1 parent d5415a3 commit a2377cc

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

src/lib/vec.rs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,10 +193,26 @@ fn tail<T>(v: [mutable? T]) : is_not_empty(v) -> [T] {
193193
ret slice(v, 1u, len(v));
194194
}
195195

196+
// FIXME: This name is sort of confusing next to init_fn, etc
197+
// but this is the name haskell uses for this function,
198+
// along with head/tail/last.
199+
/*
200+
Function: init
201+
202+
Returns all but the last elemnt of a vector
203+
204+
Preconditions:
205+
`v` is not empty
206+
*/
207+
fn init<T>(v: [mutable? T]) -> [T] {
208+
assert len(v) != 0u;
209+
slice(v, 0u, len(v) - 1u)
210+
}
211+
196212
/*
197213
Function: last
198214
199-
Returns the last element of `v`
215+
Returns the last element of a vector
200216
201217
Returns:
202218

src/test/stdtest/vec.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import std::vec::*;
55
import std::option;
66
import std::option::none;
77
import std::option::some;
8+
import std::task;
89

910
fn square(n: uint) -> uint { ret n * n; }
1011

@@ -443,6 +444,31 @@ fn reversed_mut() {
443444
assert (v2[1] == 10);
444445
}
445446

447+
#[test]
448+
fn init() {
449+
let v = vec::init([1, 2, 3]);
450+
assert v == [1, 2];
451+
}
452+
453+
#[cfg(target_os = "linux")]
454+
#[cfg(target_os = "mac")]
455+
#[test]
456+
fn init_empty() {
457+
458+
let r = task::join(
459+
task::spawn_joinable((), fn (&&_i: ()) {
460+
task::unsupervise();
461+
vec::init::<int>([]);
462+
}));
463+
assert r == task::tr_failure
464+
}
465+
466+
// FIXME: Windows can't undwind
467+
#[cfg(target_os = "win32")]
468+
#[test]
469+
#[ignore]
470+
fn init_empty() { }
471+
446472
// Local Variables:
447473
// mode: rust;
448474
// fill-column: 78;

0 commit comments

Comments
 (0)