Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement List's any function #12132

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/libcollections/list.rs
Original file line number Diff line number Diff line change
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