I am trying to check if all the characters in a given string is uppercase here but the below code results in true
. Am I doing something wrong out here?
fn main() {
let message = ":) ?";
let k:bool = message
.chars()
.filter(|x| x.is_alphabetic())
// .collect();
.all(|x| x.is_uppercase());
//for val in message.chars() {
// println!("{} - {} - {}", val, val.is_uppercase(), val.is_alphabetic());
//}
println!("{:?}", k);
}
CodePudding user response:
The code works fine. Since there are no elements in your playground example, it returns true. I don't remember the name for that concept but there's a sort of "trivial truth" in logic to statements like "There are no hats in this room. Therefore, every hat in this room is blue". Since there is no counterexample (a non blue hat), it can't be false. Here's how the std::iter documentation specifies this: "(...) An empty iterator returns true."
CodePudding user response:
let message = ":) ?";
let k: bool = message
.chars() // Elements: [':', ')', ' ', '?']
.filter(|x| x.is_alphabetic()) // Elements: [] (no element is alphabetic, so this is an empty iterator)
.all(|x| x.is_uppercase()); // true (.all() is always true for empty iterators)
It's unclear what you are attempting to do, so all we can do is show you why the code behaves the way it behaves.