Skip to content

Commit 838c62b

Browse files
committed
auto merge of #12132 : brunoabinader/rust/list-matches-predicate, r=alexcrichton
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).
2 parents 4f16e51 + cb1fad3 commit 838c62b

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/libcollections/list.rs

+29
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,26 @@ pub fn find<T:Clone>(ls: @List<T>, f: |&T| -> bool) -> Option<T> {
6363
};
6464
}
6565

66+
/**
67+
* Returns true if a list contains an element that matches a given predicate
68+
*
69+
* Apply function `f` to each element of `ls`, starting from the first.
70+
* When function `f` returns true then it also returns true. If `f` matches no
71+
* elements then false is returned.
72+
*/
73+
pub fn any<T>(ls: @List<T>, f: |&T| -> bool) -> bool {
74+
let mut ls = ls;
75+
loop {
76+
ls = match *ls {
77+
Cons(ref hd, tl) => {
78+
if f(hd) { return true; }
79+
tl
80+
}
81+
Nil => return false
82+
}
83+
};
84+
}
85+
6686
/// Returns true if a list contains an element with the given value
6787
pub fn has<T:Eq>(ls: @List<T>, elt: T) -> bool {
6888
let mut found = false;
@@ -222,6 +242,15 @@ mod tests {
222242
assert_eq!(list::find(empty, match_), option::None::<int>);
223243
}
224244

245+
#[test]
246+
fn test_any() {
247+
fn match_(i: &int) -> bool { return *i == 2; }
248+
let l = from_vec([0, 1, 2]);
249+
let empty = @list::Nil::<int>;
250+
assert_eq!(list::any(l, match_), true);
251+
assert_eq!(list::any(empty, match_), false);
252+
}
253+
225254
#[test]
226255
fn test_has() {
227256
let l = from_vec([5, 8, 6]);

0 commit comments

Comments
 (0)