Iter<Bool> -> Bool // "any" function

I have the following:

T: some type
v: Vec<T>
f: &T -> bool
x = v.iter().map(|x| f(x)).????;

So at this point, ???? is looking at an Iter<bool>

Is there a way to get an "any" over this -- where we return true if any of the returned bools is true; otherwise return false.

v.iter().any(|x| f(x))

3 Likes

And with eta-reduction:

v.iter().any(f)

which is neat (only) when f is aptly named:

fn contains_None<T> (elems: &'_ [Option<T>])
  -> bool
{
    elems.iter().any(Option::is_none)
}

If you need to access the value having lead to the predicate returning true, you can use .position() to get the index of the value, or .find() to get the desired value directly.

  • Note: when iterating over a str chars, you should use
    .char_indices()
    .find_map(|(i, c)| if predicate(c) { Some(i) } else { None })
    
    rather than
    .chars()
    .position(predicate)
    
    if intending to use the obtained number to index the str.
3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.