scala forall 并存在输出,是否有意义 [英] scala forall and exists output , does it make sense
本文介绍了scala forall 并存在输出,是否有意义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
对于上面2个谓词,既然列表中不存在元素,那么forall怎么返回true呢?我很困惑.有人能帮忙解释一下吗?
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?
推荐答案
您可以重新表述为 forall
意味着列表中的任何元素都不会违反给定的谓词.如果有没有元素,它们都不会违反它.
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.
forall
如果集合为空,则显式返回 true:
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
}
这篇关于scala forall 并存在输出,是否有意义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文