Applying logical and to list of boolean values

user3277752 picture user3277752 · Mar 19, 2014 · Viewed 20k times · Source

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?

Answer

drexin picture drexin · Mar 19, 2014

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.