Scala forall and there is a conclusion whether it makes sense

scala> val l = List()
l: List[Nothing] = List()

scala> l.forall(x=>false)
res0: Boolean = true

scala> l.forall(x=>true)
res1: Boolean = true

scala> l.exists(x=>false)
res2: Boolean = false

scala> l.exists(x=>true)
res3: Boolean = false

For above predicate 2, now that there is no element in the list, how is it that true returns true? I'm confused. could you help explain?

+5
source share
3 answers

You can rephrase, which forallmeans that none of the elements in the list violate this predicate. In the absence of elements, none of them violates it.

The source code forallexplicitly returns true if the collection is empty:

def forall(p: A => Boolean): Boolean = {
    var these = this
    while (!these.isEmpty) {
       ...
    }
    true
}
+14
source

The semantics of these methods was chosen so as to be consistent with the semantics of the universal and the quantifier of existence in formal logic.

forall - true, , false. , forall .

exists . true, , true. , , exists false.

+8

The unit of connection (i.e. and) is equal true, while the unit of disjunction (i.e. or) isfalse

Consider a list lstwith items n.

lst.forall(f) equivalently

true && f(lst(0)) && ... && f(lst(n-1))

lst.exists(f) equivalently

false || f(lst(0)) || ... || f(lst(n-1))

In the case of an empty list, there is only the first term in the above expressions.

0
source

All Articles