diff options
| author | Bruno de Oliveira Abinader <bruno.d@partner.samsung.com> | 2014-02-09 13:03:47 -0400 |
|---|---|---|
| committer | Bruno de Oliveira Abinader <bruno.d@partner.samsung.com> | 2014-02-10 08:36:48 -0400 |
| commit | cb1fad3b28475eceff3de26380297a2c92fe5deb (patch) | |
| tree | 8fbdef5f1c17dba0bdd0330dd864d3b17e2fb63c | |
| parent | d440a569bb34ef31af7eff26105a115120a85e80 (diff) | |
| download | rust-cb1fad3b28475eceff3de26380297a2c92fe5deb.tar.gz rust-cb1fad3b28475eceff3de26380297a2c92fe5deb.zip | |
Implement List's any() function
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).
| -rw-r--r-- | src/libcollections/list.rs | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/src/libcollections/list.rs b/src/libcollections/list.rs index 06ec24bdc9d..0dc13aa2b49 100644 --- a/src/libcollections/list.rs +++ b/src/libcollections/list.rs @@ -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; @@ -223,6 +243,15 @@ mod tests { } #[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]); let empty = @list::Nil::<int>; |
