Skip to content

Commit

Permalink
Implement List's any() function
Browse files Browse the repository at this point in the history
This is needed for cases where we only need to know if a list item
matches the given predicate (eg. in Servo, we need to know if attributes
from different DOM elements are equal).
  • Loading branch information
brunoabinader committed Feb 10, 2014
1 parent d440a56 commit cb1fad3
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/libcollections/list.rs
Expand Up @@ -63,6 +63,26 @@ pub fn find<T:Clone>(ls: @List<T>, f: |&T| -> bool) -> Option<T> {
};
}

/**
* Returns true if a list contains an element that matches a given predicate
*
* Apply function `f` to each element of `ls`, starting from the first.
* When function `f` returns true then it also returns true. If `f` matches no
* elements then false is returned.
*/
pub fn any<T>(ls: @List<T>, f: |&T| -> bool) -> bool {
let mut ls = ls;
loop {
ls = match *ls {
Cons(ref hd, tl) => {
if f(hd) { return true; }
tl
}
Nil => return false
}
};
}

/// Returns true if a list contains an element with the given value
pub fn has<T:Eq>(ls: @List<T>, elt: T) -> bool {
let mut found = false;
Expand Down Expand Up @@ -222,6 +242,15 @@ mod tests {
assert_eq!(list::find(empty, match_), option::None::<int>);
}

#[test]
fn test_any() {
fn match_(i: &int) -> bool { return *i == 2; }
let l = from_vec([0, 1, 2]);
let empty = @list::Nil::<int>;
assert_eq!(list::any(l, match_), true);
assert_eq!(list::any(empty, match_), false);
}

#[test]
fn test_has() {
let l = from_vec([5, 8, 6]);
Expand Down

5 comments on commit cb1fad3

@bors
Copy link
Contributor

@bors bors commented on cb1fad3 Feb 10, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bors
Copy link
Contributor

@bors bors commented on cb1fad3 Feb 10, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merging brunoabinader/rust/list-matches-predicate = cb1fad3 into auto

@bors
Copy link
Contributor

@bors bors commented on cb1fad3 Feb 10, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

brunoabinader/rust/list-matches-predicate = cb1fad3 merged ok, testing candidate = 838c62b

@bors
Copy link
Contributor

@bors bors commented on cb1fad3 Feb 10, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bors
Copy link
Contributor

@bors bors commented on cb1fad3 Feb 10, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fast-forwarding master to auto = 838c62b

Please sign in to comment.