gpt4 book ai didi

scala - 如何在 x :Myclass => Boolean to get the conjunction? 的列表中使用左折叠

转载 作者:行者123 更新时间:2023-12-05 00:34:13 24 4
gpt4 key购买 nike

我有一些过滤器表示为函数 List(MyClass => Boolean) 的列表。我试图获得所有成员的逻辑连接(AND)。我有一种感觉,我可以在这里使用折叠。但我没有得到语法,尤其是关于如何将 MyClass 参数传递给函数的语法。

最佳答案

您可以使用 foldLeft在这里,但是 forall好多了:

def check[A](filters: Seq[A => Boolean])(a: A) = filters.forall(_(a))

其工作原理如下:
scala> val filters = Seq[Int => Boolean]((_ > 0), (_ % 2 == 1), (_ < 1000))
filters: Seq[Int => Boolean] = List(<function1>, <function1>, <function1>)

scala> check(filters)(10)
res0: Boolean = false

scala> check(filters)(103)
res1: Boolean = true

它具有懒惰的额外优势:
scala> check(filters :+ { i: Int => print(i); true })(10)
res2: Boolean = false

未应用最后一个过滤器(有副作用),因为第二个过滤器失败。

关于scala - 如何在 x :Myclass => Boolean to get the conjunction? 的列表中使用左折叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11002339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com