Applying logical and to list of boolean values

2020-05-25 05:25发布

问题:

Consider the following list of Boolean values in Scala

List(true, false, false, true)

How would you using either foldRight or foldLeft emulate the function of performing a logical AND on all of the values within the list?

回答1:

val l = List(true, false, false, true)
val andAll = l.foldLeft(true)(_ && _)


回答2:

Instead of using foldLeft/Right, you can also use forall(identity) for the logical AND, or exists(identity) for the logical OR.

edit: The benefit of these functions is the early exit. If forall hits a false or exists a true, they will immediately return.



回答3:

Without initial value as in foldLeft,

List(true, false, false, true).reduce(_&&_)

Yet this works not for List.empty[Boolean].



回答4:

I like the forAll approach best so long as it fits your use case. It exits early which is great. However, if that doesn't fit here's another, only marginally more complex, approach.

With reduceOption you get no early exit, but you can clearly specify the value for the case where the list is empty.

val l = List(true, false, false, true)
val andAll = l.reduceOption(_ && _).getOrElse(false)