scala 将逻辑和应用于布尔值列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22518773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:07:11  来源:igfitidea点击:

Applying logical and to list of boolean values

scalabooleanlogical-operatorsfold

提问by user3277752

Consider the following list of Boolean values in Scala

考虑以下 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?

您将如何使用 foldRight 或 foldLeft 模拟对列表中的所有值执行逻辑 AND 的功能?

采纳答案by Lee

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

回答by drexin

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

除了使用foldLeft/Right,您还可以forall(identity)用于逻辑 AND 或exists(identity)逻辑 OR。

edit: The benefit of these functions is the early exit. If forallhits a falseor existsa true, they will immediately return.

编辑:这些功能的好处是提前退出。如果forall命中 afalseexistsa true,它们将立即返回。

回答by elm

Without initial value as in foldLeft,

没有初始值,如foldLeft

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

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

然而这不适用于List.empty[Boolean].

回答by sfosdal

I like the forAllapproach 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.

forAll最喜欢这种方法,只要它适合您的用例。它很早就退出了,这很棒。但是,如果这不适合这里,则是另一种稍微复杂的方法。

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

使用 reduceOption 您不会提前退出,但您可以明确指定列表为空的情况的值。

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