简体   繁体   English

Scala:“任何”和“所有”功能

[英]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? 这些属性中的一个是否适用于它?

  1. predefined somewhere in the Scala libs 预定义在Scala库中的某个位置
  2. circumstantial, and faster written as some one-liner 间接的,更快写成一些单行
  3. wrong (I didn't test it, sorry ;)) 错了(我没试过,对不起;))

*actually SML, but that's 99% the same, but known by nobody under the sun. *实际上是SML,但这是99%相同,但在阳光下没有人知道。

  1. 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 
  2. You can make it more performant using a for loop with a break (from scala.util.control.Breaks ). 你可以使用带有breakfor循环(来自scala.util.control.Breaks )使其更scala.util.control.Breaks (See the standard library implementation of exists and forall .) (参见existsforall的标准库实现。)

  3. It's correct. 这是正确的。

Methods exist on the Traversable trait which are equivalent to any and all : Traversable trait上存在的方法相当于anyall

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
  1. No it isn't predifined with those names. 不,它没有被这些名称所预测。 You can use exists from Traversable package. 您可以使用Traversable包中的exists
  2. 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)

  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM