Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何实施";或;在scala过滤器中?_Scala - Fatal编程技术网

如何实施";或;在scala过滤器中?

如何实施";或;在scala过滤器中?,scala,Scala,我试图在scala中实现一个“或”过滤列表 list.filter(_ % 3 ==0 || _ % 5 ==0) 但我得到了这个错误: 错误:参数数量错误;期望值=1 那么如何将其分组为一个参数。如果参数在函数表达式中只出现一次,则只能使用占位符语法。否则,必须显式声明函数参数: list.filter(x => x % 3 == 0 || x % 5 == 0) 多个占位符可扩展为多个方法参数。请尽量精简: list.filter(x => x % 3 ==0 ||

我试图在scala中实现一个“或”过滤列表

    list.filter(_ % 3 ==0 || _ % 5 ==0)
但我得到了这个错误:

错误:参数数量错误;期望值=1


那么如何将其分组为一个参数。

如果参数在函数表达式中只出现一次,则只能使用占位符语法。否则,必须显式声明函数参数:

list.filter(x => x % 3 == 0 || x % 5 == 0)

多个占位符可扩展为多个方法参数。

请尽量精简:

list.filter(x => x % 3 ==0 || x % 5 ==0)
下划线不起作用,因为第n个uu扩展为第n个参数,如下所示:

list.filter((x,y) => x % 3 ==0 || y % 5 ==0)

最简单的解决方案是使用:

list.filter(x => (x % 3 == 0) || (x % 5 == 0))
如果你想变得花哨并实现一个“或”,看看我是如何通过拉皮条来实现的:。为皮条客提供的简单解决方案是:

trait Pred1[A] extends (A => Boolean){
  self =>

  def or[AA >: A](that: AA => Boolean) = new Pred1[A]{
    def apply(arg: A) = self(arg) || that(arg)
  }
}

//and somewhere in the code
implicit def f2p[A](f: A => Boolean) = new Pred1[A]{ def apply(arg: A) = f(arg) }
以“and”、“xor”、“nxor”、“nor”和“nand”等表示。然后,您只需提出两个传递到过滤器的函数


请注意,我可能会用一个type类来代替pimping,并在另一个分支中玩弄一些想法,但几乎没有时间真正深入研究它。

功能替代方案:

val or = (xs: List[Int => Boolean]) => (x: Int) => xs.exists(_(x))

List(0, 1, 2, 3, 4, 5, 6).filter(or(List(_ % 3 == 0, _ % 5 == 0)))
或者更简单:

val or = { def or(xs: (Int => Boolean)*) = (x: Int) => xs.exists(_(x)); or _}
List(0, 1, 2, 3, 4, 5, 6).filter(or(_ % 3 == 0, _ % 5 == 0))
更新:第二个版本似乎不适用于Scala 2.10,因此最好使用以下方法:

def or[T](xs: (T => Boolean)*) = (x: T) => xs.exists(_(x))

我建议你也去看看