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 2 predicate, now that no element exists in the list, how come forall return true? I am confused. could you somebody help explain?
You could rephrase that forall
means that none of the elements of the list violate the given predicate. In case there are no elements, none of them violates it.
The source code of forall
explicitly returns true if a collection is empty:
def forall(p: A => Boolean): Boolean = {
var these = this
while (!these.isEmpty) {
...
}
true
}
The semantics of these methods was chosen to be coherent with the semantics of the universal and the existential quantifier in formal logic.
Method forall
acts as the universal quantifier - it returns true
if there is no element in the collection for which the predicate is false
. If there are no elements, then the predicate is never false and forall
is true.
Method exists
acts as the existential quantifier. It returns true
if there is at least one element for which the predicate is true
. If there are no elements, then the predicate is never true and exists
returns false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With