Scala:“任何”和“全部”;功能
我的 Haskell* 有点生锈了,所以我可以想象我错过了显而易见的事情:
def any[A](s: Traversable[A], f: A => Boolean): Boolean = {
s.foldLeft(false)((bool, elem) => bool || f(elem))
}
这些属性之一是否适用于它?
- 在Scala libs
- 环境中的某个地方预定义的,并且更快地写成一些单行
- 错误(我没有测试它,抱歉;))
*实际上是SML,但99%相同,但在阳光下无人知晓。
my Haskell* is a bit rusty, so i can imagine that I’m missing the obvious:
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 ;))
*actually SML, but that’s 99% the same, but known by nobody under the sun.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它是预定义的,称为
存在
。forall
将是您正在寻找的“all”函数。您可以使用带有
break
的for
循环(来自scala.util.control.Breaks
)来提高其性能。 (请参阅exists
和forall
的标准库实现。)这是正确的。
It's predefined and is called
exists
. Andforall
would be the "all" function you are looking for.You can make it more performant using a
for
loop with abreak
(fromscala.util.control.Breaks
). (See the standard library implementation ofexists
andforall
.)It's correct.
Traversable 特征上存在的方法相当于
any
和all
:Methods exist on the Traversable trait which are equivalent to
any
andall
:exists
。您的实现的最大缺点是,当对于任何
any
,如果有任何为真,如果已经可以给您答案时,将需要消耗您的所有可遍历性。对于全部
也是如此。但我们可以很容易地实现这一点,这样它就不会评估整个序列。另一种解决方案是为此类操作实现一个 monad。然后你会调用:a and b and c
相当于a.and(b).and(c)
这是正确的。
顺便说一句,我发现缺少的另一个函数是 sum 函数。
exists
from 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 c
which is equivalent toa.and(b).and(c)
It is correct.
BTW, another function that I find missing is a
sum
function.exists
怎么样:它位于 Traversable< /a>.
How about
exists
:It's on Traversable.