Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
825 views
in Technique[技术] by (71.8m points)

scala - Making sense of forall and exists output on empty list

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...