Skip to content

Commit fed034c

Browse files
committed
Refactored list::head() to be based on List<T>
1 parent 45fd63a commit fed034c

File tree

2 files changed

+19
-21
lines changed

2 files changed

+19
-21
lines changed

src/libcollections/list.rs

+14-16
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,14 @@ impl<T> List<T> {
5353
next: None
5454
}
5555
}
56+
57+
/// Returns the first element of a list
58+
pub fn head<'a>(&'a self) -> Option<&'a T> {
59+
match *self {
60+
Nil => None,
61+
Cons(ref head, _) => Some(head)
62+
}
63+
}
5664
}
5765

5866
impl<T> Container for List<T> {
@@ -78,15 +86,6 @@ pub fn tail<T>(list: @List<T>) -> @List<T> {
7886
}
7987
}
8088

81-
/// Returns the first element of a list
82-
pub fn head<T:Clone>(list: @List<T>) -> T {
83-
match *list {
84-
Cons(ref head, _) => (*head).clone(),
85-
// makes me sad
86-
_ => fail!("head invoked on empty list")
87-
}
88-
}
89-
9089
/// Appends one list to another
9190
pub fn append<T:Clone + 'static>(list: @List<T>, other: @List<T>) -> @List<T> {
9291
match *list {
@@ -118,7 +117,7 @@ fn push<T:Clone>(ll: &mut @list<T>, vv: T) {
118117

119118
#[cfg(test)]
120119
mod tests {
121-
use list::{List, Nil, head, tail};
120+
use list::{List, Nil, tail};
122121
use list;
123122

124123
#[test]
@@ -145,14 +144,13 @@ mod tests {
145144
#[test]
146145
fn test_from_vec() {
147146
let list = @List::from_vec([0, 1, 2]);
147+
assert_eq!(list.head().unwrap(), &0);
148148

149-
assert_eq!(head(list), 0);
150-
151-
let tail_l = tail(list);
152-
assert_eq!(head(tail_l), 1);
149+
let mut tail = tail(list);
150+
assert_eq!(tail.head().unwrap(), &1);
153151

154-
let tail_tail_l = tail(tail_l);
155-
assert_eq!(head(tail_tail_l), 2);
152+
tail = tail(tail);
153+
assert_eq!(tail.head().unwrap(), &2);
156154
}
157155

158156
#[test]

src/test/run-pass/non-boolean-pure-fns.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,19 @@
1414

1515
extern crate collections;
1616

17-
use collections::list::{List, Cons, Nil, head};
17+
use collections::list::{List, Cons, Nil};
1818

19-
fn pure_length_go<T:Clone>(ls: @List<T>, acc: uint) -> uint {
19+
fn pure_length_go<T>(ls: @List<T>, acc: uint) -> uint {
2020
match *ls { Nil => { acc } Cons(_, tl) => { pure_length_go(tl, acc + 1u) } }
2121
}
2222

23-
fn pure_length<T:Clone>(ls: @List<T>) -> uint { pure_length_go(ls, 0u) }
23+
fn pure_length<T>(ls: @List<T>) -> uint { pure_length_go(ls, 0u) }
2424

25-
fn nonempty_list<T:Clone>(ls: @List<T>) -> bool { pure_length(ls) > 0u }
25+
fn nonempty_list<T>(ls: @List<T>) -> bool { pure_length(ls) > 0u }
2626

2727
fn safe_head<T:Clone>(ls: @List<T>) -> T {
2828
assert!(!ls.is_empty());
29-
return head(ls);
29+
return ls.head().unwrap().clone();
3030
}
3131

3232
pub fn main() {

0 commit comments

Comments
 (0)