Scala:“任何”和“所有”函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6390797/
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
Scala: “any” and “all” functions
提问by flying sheep
my Haskell* is a bit rusty, so i can imagine that I'm missing the obvious:
我的 Haskell* 有点生疏,所以我可以想象我错过了明显的:
def any[A](s: Traversable[A], f: A => Boolean): Boolean = {
s.foldLeft(false)((bool, elem) => bool || f(elem))
}
Does one of these properties apply to the it?
这些属性之一是否适用于它?
- predefined somewhere in the Scala libs
- circumstantial, and faster written as some one-liner
- wrong (I didn't test it, sorry ;))
- 在 Scala 库中的某处预定义
- 间接的,更快地写成一些单行
- 错误(我没有测试过,抱歉;))
*actually SML, but that's 99% the same, but known by nobody under the sun.
*实际上是 SML,但 99% 相同,但在阳光下无人知晓。
回答by missingfaktor
It's predefined and is called
exists. Andforallwould be the "all" function you are looking for.scala> Vector(3, 4, 5).exists(_ % 2 == 0) res1: Boolean = true scala> Vector(3, 4, 5).forall(_ % 2 == 0) res2: Boolean = falseYou can make it more performant using a
forloop with abreak(fromscala.util.control.Breaks). (See the standard library implementation ofexistsandforall.)It's correct.
它是预定义的,称为
exists. 并且forall将是您正在寻找的“全部”功能。scala> Vector(3, 4, 5).exists(_ % 2 == 0) res1: Boolean = true scala> Vector(3, 4, 5).forall(_ % 2 == 0) res2: Boolean = false您可以使用
for带有break(fromscala.util.control.Breaks)的循环提高性能。(参见标准库实现的exists和forall。)这是正确的。
回答by David Winslow
Methods exist on the Traversable trait which are equivalent to anyand all:
Traversable trait 中存在的方法等价于any和all:
def all[A](xs: Traversable[A], p: A => Boolean): Boolean = xs forall p
def any[A](xs: Traversable[A], p: A => Boolean): Boolean = xs exists p
回答by rafalotufo
- No it isn't predifined with those names. You can use
existsfrom Traversable package. The biggest disadvantage of your implementation is that will necessary consume all of your traversible, when, for
any, if any is true, if could already give you your answer. The same goes forall. But one could easily implement this so that it doesn't evaluate the whole sequence. Another solution would be to implement a monad for this type of operation. Then you would call:a and b and cwhich is equivalent toa.and(b).and(c)It is correct.
- 不,它没有预先定义这些名称。您可以
exists从 Traversable 包中使用。 您的实现的最大缺点是将有必要消耗您所有的可遍历对象,当,for
any,如果为真,如果已经可以给您答案。也是如此all。但是人们可以很容易地实现这一点,这样它就不会评估整个序列。另一种解决方案是为这种类型的操作实现一个 monad。然后你会打电话:a and b and c这相当于a.and(b).and(c)它是正确的。
BTW, another function that I find missing is a sumfunction.
顺便说一句,我发现缺少的另一个功能是一个sum功能。
回答by Adam Rabung
How about exists:
怎么样exists:
scala> List(1,2,3).exists(_ > 2)
res12: Boolean = true
It's on Traversable.

