Scala forall 示例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12547235/
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 04:33:31  来源:igfitidea点击:

Scala forall example?

scala

提问by Jus12

I tried Google search and could not find a decent forallexample. What does it do? Why does it take a boolean function?

我尝试了谷歌搜索,但找不到像样的forall例子。它有什么作用?为什么它需要一个布尔函数?

Please point me to a reference (except the Scaladoc).

请给我一个参考(Scaladoc 除外)。

回答by dhg

The forallmethod takes a function pthat returns a Boolean. The semantics of forallsays: return trueif for every xin the collection, p(x)is true.

forall方法采用一个p返回布尔值的函数。语义forall说:true如果对于x集合中的每个都返回,p(x)则为真。

So:

所以:

List(1,2,3).forall(x => x < 3)

means: trueif 1, 2, and 3 are less than 3, falseotherwise. In this case, it will evaluate to falsesince it is not the case all elements are less than 3: 3 is not less than 3.

意思是:true如果1、2、3都小于3,false否则。在这种情况下,它将评估为,false因为并非所有元素都小于 3:3 不小于 3。

There is a similar method existsthat returns trueif there is at least oneelement xin the collection such that p(x)is true.

如果集合中至少有一个元素为真existstrue则有一个类似的方法返回。xp(x)

So:

所以:

List(1,2,3).exists(x => x < 3)

means: trueif at least one of1, 2, and 3 is less than 3, falseotherwise. In this case, it will evaluate to truesince it is the case some element is less than 3: e.g. 1 is less than 3.

意思是:true如果1、2、3中至少有一个小于3,false否则。在这种情况下,它将评估为,true因为某些元素小于 3:例如 1 小于 3。

回答by James Raitsev

A quick example of how you can play with this function using a Scalascript.

一个关于如何使用Scala脚本玩这个函数的快速示例。

create a myScript.scalafile with

创建一个myScript.scala文件

println(args.forall(p => (p.equals("a"))))

and call it with

并调用它

scala myScript.scala a a a  // true
scala myScript.scala a b c  // false

回答by Johnny

Scala's forallis also a great tool to do something like applying logical andto a list of boolean values with the early exist:

Scalaforall也是一个很好的工具,可以执行诸如将逻辑布尔值列表应用于早期存在的操作

val evalResults: List[Boolean] = List(evaluateFunc1(), evaluateFunc2(), evaluateFunc3(), evaluateFunc4(), evaluateFunc5())

evalResults.forall(result => result == true)