Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making sense of forall and exists output on empty list

Tags:

scala

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?

like image 342
Russel Yang Avatar asked Apr 12 '13 22:04

Russel Yang


2 Answers

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
}
like image 197
Alex Yarmula Avatar answered Sep 23 '22 10:09

Alex Yarmula


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.

like image 43
axel22 Avatar answered Sep 20 '22 10:09

axel22