From fed034c402eb22b60fb9d7581e720bb0010dae65 Mon Sep 17 00:00:00 2001 From: Bruno de Oliveira Abinader Date: Mon, 24 Feb 2014 23:34:26 -0400 Subject: Refactored list::head() to be based on List --- src/libcollections/list.rs | 30 ++++++++++++++---------------- src/test/run-pass/non-boolean-pure-fns.rs | 10 +++++----- 2 files changed, 19 insertions(+), 21 deletions(-) diff --git a/src/libcollections/list.rs b/src/libcollections/list.rs index 05e60d07df8..a922c247b2f 100644 --- a/src/libcollections/list.rs +++ b/src/libcollections/list.rs @@ -53,6 +53,14 @@ impl List { 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 Container for List { @@ -78,15 +86,6 @@ pub fn tail(list: @List) -> @List { } } -/// Returns the first element of a list -pub fn head(list: @List) -> 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(list: @List, other: @List) -> @List { match *list { @@ -118,7 +117,7 @@ fn push(ll: &mut @list, 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 tail_l = tail(list); - assert_eq!(head(tail_l), 1); + let mut tail = tail(list); + assert_eq!(tail.head().unwrap(), &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] diff --git a/src/test/run-pass/non-boolean-pure-fns.rs b/src/test/run-pass/non-boolean-pure-fns.rs index 9cbf80c3105..66bb2e702be 100644 --- a/src/test/run-pass/non-boolean-pure-fns.rs +++ b/src/test/run-pass/non-boolean-pure-fns.rs @@ -14,19 +14,19 @@ extern crate collections; -use collections::list::{List, Cons, Nil, head}; +use collections::list::{List, Cons, Nil}; -fn pure_length_go(ls: @List, acc: uint) -> uint { +fn pure_length_go(ls: @List, acc: uint) -> uint { match *ls { Nil => { acc } Cons(_, tl) => { pure_length_go(tl, acc + 1u) } } } -fn pure_length(ls: @List) -> uint { pure_length_go(ls, 0u) } +fn pure_length(ls: @List) -> uint { pure_length_go(ls, 0u) } -fn nonempty_list(ls: @List) -> bool { pure_length(ls) > 0u } +fn nonempty_list(ls: @List) -> bool { pure_length(ls) > 0u } fn safe_head(ls: @List) -> T { assert!(!ls.is_empty()); - return head(ls); + return ls.head().unwrap().clone(); } pub fn main() { -- cgit 1.4.1-3-g733a5