diff --git a/src/libcollections/list.rs b/src/libcollections/list.rs index 0dc13aa2b49e2..dec145c4fb4d7 100644 --- a/src/libcollections/list.rs +++ b/src/libcollections/list.rs @@ -63,6 +63,26 @@ pub fn find(ls: @List, f: |&T| -> bool) -> Option { }; } +/** + * Returns true if all list elements matches a given predicate + * + * Apply function `f` to each element of `ls`, starting from the first. + * When function `f` returns false then it also returns false. If `f` matches + * all elements then true is returned. + */ +pub fn all(ls: @List, f: |&T| -> bool) -> bool { + let mut ls = ls; + loop { + ls = match *ls { + Cons(ref hd, tl) => { + if !f(hd) { return false; } + tl + } + Nil => return true + } + } +} + /** * Returns true if a list contains an element that matches a given predicate * @@ -242,6 +262,15 @@ mod tests { assert_eq!(list::find(empty, match_), option::None::); } + #[test] + fn test_all() { + fn is_even(i: &int) -> bool { return *i % 2 == 0; } + let l_even = from_vec([2, 4, 6]); + let l_odd = from_vec([1, 3, 5]); + assert_eq!(list::all(l_even, match_), true); + assert_eq!(list::all(l_odd, match_), false); + } + #[test] fn test_any() { fn match_(i: &int) -> bool { return *i == 2; }