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?
With * operator The * operator can repeat the same value required number of times. We use it to create a list with a Boolean value.
A boolean list ("blist") is a list that has no holes and contains only true and false . Boolean lists can be represented in an efficient compact form, see 22.5 for details. Boolean lists are lists and all operations for lists are therefore applicable to boolean lists.
You can use the truth value of Boolean expressions to decide the course of action of your programs. As you can see in this code, Python implements bool as a subclass of int with two possible values, True and False . These values are built-in constants in Python.
The AND && operator does the following: Evaluates operands from left to right. For each operand, converts it to a boolean. If the result is false , stops and returns the original value of that operand.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With