1
Fork 0

Refactored list::head() to be based on List<T>

This commit is contained in:
Bruno de Oliveira Abinader 2014-02-24 23:34:26 -04:00
parent 45fd63a8b7
commit fed034c402
2 changed files with 19 additions and 21 deletions

View file

@ -53,6 +53,14 @@ impl<T> List<T> {
next: None
}
}
/// Returns the first element of a list
pub fn head<'a>(&'a self) -> Option<&'a T> {
match *self {
Nil => None,
Cons(ref head, _) => Some(head)
}
}
}
impl<T> Container for List<T> {
@ -78,15 +86,6 @@ pub fn tail<T>(list: @List<T>) -> @List<T> {
}
}
/// Returns the first element of a list
pub fn head<T:Clone>(list: @List<T>) -> T {
match *list {
Cons(ref head, _) => (*head).clone(),
// makes me sad
_ => fail!("head invoked on empty list")
}
}
/// Appends one list to another
pub fn append<T:Clone + 'static>(list: @List<T>, other: @List<T>) -> @List<T> {
match *list {
@ -118,7 +117,7 @@ fn push<T:Clone>(ll: &mut @list<T>, vv: T) {
#[cfg(test)]
mod tests {
use list::{List, Nil, head, tail};
use list::{List, Nil, tail};
use list;
#[test]
@ -145,14 +144,13 @@ mod tests {
#[test]
fn test_from_vec() {
let list = @List::from_vec([0, 1, 2]);
assert_eq!(list.head().unwrap(), &0);
assert_eq!(head(list), 0);
let mut tail = tail(list);
assert_eq!(tail.head().unwrap(), &1);
let tail_l = tail(list);
assert_eq!(head(tail_l), 1);
let tail_tail_l = tail(tail_l);
assert_eq!(head(tail_tail_l), 2);
tail = tail(tail);
assert_eq!(tail.head().unwrap(), &2);
}
#[test]

View file

@ -14,19 +14,19 @@
extern crate collections;
use collections::list::{List, Cons, Nil, head};
use collections::list::{List, Cons, Nil};
fn pure_length_go<T:Clone>(ls: @List<T>, acc: uint) -> uint {
fn pure_length_go<T>(ls: @List<T>, acc: uint) -> uint {
match *ls { Nil => { acc } Cons(_, tl) => { pure_length_go(tl, acc + 1u) } }
}
fn pure_length<T:Clone>(ls: @List<T>) -> uint { pure_length_go(ls, 0u) }
fn pure_length<T>(ls: @List<T>) -> uint { pure_length_go(ls, 0u) }
fn nonempty_list<T:Clone>(ls: @List<T>) -> bool { pure_length(ls) > 0u }
fn nonempty_list<T>(ls: @List<T>) -> bool { pure_length(ls) > 0u }
fn safe_head<T:Clone>(ls: @List<T>) -> T {
assert!(!ls.is_empty());
return head(ls);
return ls.head().unwrap().clone();
}
pub fn main() {