I have written the following Rust function, which contains a closure.
fn has_a_none_element(&self) -> bool {
let elements_is_none =
self.elements.iter().flatten().map(Option::is_none);
let optional_any_is_none =
elements_is_none.reduce(
|lhs, rhs| {
lhs || rhs
}
);
match optional_any_is_none {
None => false,
Some(any_is_none) => any_is_none,
}
}
self.elements
is of type Vec<Vec<Option<f64>>>
, although this is not particularly important.
What is important is the closure:
|lhs, rhs| {
lhs || rhs
}
This is an "Or" function. It is the sort of thing that one might expect there to already be an inbuilt function for which could be used as part of a closure.
Does such a thing exist?
Addressing the title directly, there is no named function in the standard library to express the ||
operator. Other operators can be named like And::and
but since logical-or is only available for bool
and not custom structs, that isn't a thing.
An adjacent behavior though is available through the |
operator (a.k.a the BitOr
trait) and has identical behavior as ||
on bool
s besides short-circuiting. Using that we can get this:
use std::ops::BitOr;
let optional_any_is_none = elements_is_none.reduce(bool::bitor)
Addressing the end goal though, @interjay is correct that your entire function can be better expressed by using .any()
instead:
fn has_a_none_element(&self) -> bool {
self.elements.iter()
.flatten()
.any(Option::is_none)
}