Skip to content

Commit

Permalink
Implemented list::is_empty() based on Container trait
Browse files Browse the repository at this point in the history
  • Loading branch information
brunoabinader committed Feb 27, 2014
1 parent e589fcf commit a14d72d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 17 deletions.
25 changes: 10 additions & 15 deletions src/libcollections/list.rs
Expand Up @@ -58,6 +58,9 @@ impl<T> List<T> {
impl<T> Container for List<T> {
/// Returns the length of a list
fn len(&self) -> uint { self.iter().len() }

/// Returns true if the list is empty
fn is_empty(&self) -> bool { match *self { Nil => true, _ => false } }
}

/// Returns true if a list contains an element with the given value
Expand All @@ -69,14 +72,6 @@ pub fn has<T:Eq>(list: @List<T>, element: T) -> bool {
return found;
}

/// Returns true if the list is empty
pub fn is_empty<T>(list: @List<T>) -> bool {
match *list {
Nil => true,
_ => false
}
}

/// Returns all but the first element of a list
pub fn tail<T>(list: @List<T>) -> @List<T> {
match *list {
Expand Down Expand Up @@ -153,7 +148,7 @@ pub fn each<T>(list: @List<T>, f: |&T| -> bool) -> bool {

#[cfg(test)]
mod tests {
use list::{List, Nil, head, is_empty, tail};
use list::{List, Nil, head, tail};
use list;

#[test]
Expand All @@ -168,13 +163,13 @@ mod tests {

#[test]
fn test_is_empty() {
let empty : @list::List<int> = @List::from_vec([]);
let full1 = @List::from_vec([1]);
let full2 = @List::from_vec(['r', 'u']);
let empty : list::List<int> = List::from_vec([]);
let full1 = List::from_vec([1]);
let full2 = List::from_vec(['r', 'u']);

assert!(is_empty(empty));
assert!(!is_empty(full1));
assert!(!is_empty(full2));
assert!(empty.is_empty());
assert!(!full1.is_empty());
assert!(!full2.is_empty());
}

#[test]
Expand Down
4 changes: 2 additions & 2 deletions src/test/run-pass/non-boolean-pure-fns.rs
Expand Up @@ -14,7 +14,7 @@

extern crate collections;

use collections::list::{List, Cons, Nil, head, is_empty};
use collections::list::{List, Cons, Nil, head};

fn pure_length_go<T:Clone>(ls: @List<T>, acc: uint) -> uint {
match *ls { Nil => { acc } Cons(_, tl) => { pure_length_go(tl, acc + 1u) } }
Expand All @@ -25,7 +25,7 @@ fn pure_length<T:Clone>(ls: @List<T>) -> uint { pure_length_go(ls, 0u) }
fn nonempty_list<T:Clone>(ls: @List<T>) -> bool { pure_length(ls) > 0u }

fn safe_head<T:Clone>(ls: @List<T>) -> T {
assert!(!is_empty(ls));
assert!(!ls.is_empty());
return head(ls);
}

Expand Down

0 comments on commit a14d72d

Please sign in to comment.