[英]Scala: “any” and “all” functions
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? 这些属性中的一个是否适用于它?
*actually SML, but that's 99% the same, but known by nobody under the sun. *实际上是SML,但这是99%相同,但在阳光下没有人知道。
It's predefined and is called exists
. 它是预定义的,称为exists
。 And forall
would be the "all" function you are looking for. 而forall
将是您正在寻找的“全部”功能。
scala> Vector(3, 4, 5).exists(_ % 2 == 0) res1: Boolean = true scala> Vector(3, 4, 5).forall(_ % 2 == 0) res2: Boolean = false
You can make it more performant using a for
loop with a break
(from scala.util.control.Breaks
). 你可以使用带有break
的for
循环(来自scala.util.control.Breaks
)使其更scala.util.control.Breaks
。 (See the standard library implementation of exists
and forall
.) (参见exists
和forall
的标准库实现。)
It's correct. 这是正确的。
Methods exist on the Traversable trait which are equivalent to any
and 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
exists
from Traversable package. 您可以使用Traversable包中的exists
。 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. 您实现的最大的缺点是会消耗所需所有traversible,时,对于any
,如果有的话是真实的,如果可能已经给你答案。 The same goes for all
. all
。 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. 另一种解决方案是为这种类型的操作实现monad。 Then you would call: 然后你会打电话:
a and b and c
which is equivalent to a.and(b).and(c)
a and b and c
相当于a and b and c
a.and(b).and(c)
It is correct. 它是正确的。
BTW, another function that I find missing is a sum
function. 顺便说一句,我发现缺少的另一个函数是sum
函数。
How about exists
: 怎么样exists
:
scala> List(1,2,3).exists(_ > 2)
res12: Boolean = true
It's on Traversable . 它在Traversable上 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.