Applying logical and to list of boolean values

后端 未结 4 1200
囚心锁ツ
囚心锁ツ 2021-02-05 07:01

Consider the following list of Boolean values in Scala

List(true, false, false, true)

How would you using either foldRight or foldLeft emulate

4条回答
  •  礼貌的吻别
    2021-02-05 07:33

    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)
    

提交回复
热议问题