Why does Iterator :: all return true for an empty iterator?

Following code

fn main() {
    {
        let a: Vec<i32> = vec![1, 2, 3, 4];
        print!("{}\n", a.into_iter().all(|x| x > 1));
    }
    {
        let a: Vec<i32> = vec![];
        print!("{}\n", a.into_iter().all(|x| x > 1));
    }
}

gives me a way out

false
true

Surprisingly a.into_iter().all(|x| x > 1)returned truewhen aempty.

Having looked at the docs forIterator::all , I see that this is explicitly stated:

An empty iterator returns true.

Why was this chosen?

+6
source share
2 answers

This is a typical function convention in allalmost all programming languages, except for those that are erroneous. Conversely, anyreturns falsefor empty sequences.

, . , , . , ? , , - . conditions.all(|value| condition.fulfilled(value)) true .

all " ", , all :

fn all<F>(&mut self, f: F) -> bool
where
    F: FnMut(Self::Item) -> bool,
{
    for v in self {
        if !f(v) {
            return false;
        }
    }
    return true;
}

, - .

+11

, :

A => B (A B) !A | B ( A B).

S: for each x in X, P(x) is true ( P - ) for each x: x in X implies P(X) is true.

, , : For each x: P(x) is true or x is not in X

X , x is not in X , S .

+3

All Articles