问题
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?
回答1:
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
}
回答2:
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.
回答3:
Unit of conjunction(i.e. and) is true whereas unit of disjunction (i.e. or) is false
Consider a list lst of with n elements.
lst.forall(f) is equivalent to
true && f(lst(0)) && ... && f(lst(n-1))
lst.exists(f) is equivalent to
false || f(lst(0)) || ... || f(lst(n-1))
In case of an empty list, only first term in above expressions is there.
来源:https://stackoverflow.com/questions/15981599/scala-forall-and-exists-output-does-it-make-sense