使用多个元素和逻辑运算符过滤数组

时间:2017-08-14 09:32:25

标签: arrays scala filter

我有一个2D数组如下:

scala> testme4
res15: Array[(java.sql.Timestamp, Int, Int, Boolean)] 
   = Array((2016-11-17 15:18:50.47,13,-8,false), 
           (2016-11-17 15:18:51.37,21,-1,false), 
           (2016-11-17 15:18:51.37,22,-1,false), 
           (2016-11-17 15:18:51.86,23,-1,false), 
           (2016-11-17 15:18:52.3,24,22,false), 
           (2016-11-17 15:18:52.37,2,-2,false), 
           (2016-11-17 15:18:54.2,4,-1,false), 
           (2016-11-17 15:18:54.2,5,-7,false), 
           (2016-11-17 15:20:57.27,12,-4,false), 
           (2016-11-17 15:20:57.67,16,-1,false), 
           (2016-11-17 15:20:57.67,17,-9,false), 
           (2016-11-17 15:20:58.3,26,0,false), 
           (2016-11-17 15:20:59.35,26,0,true)
       )

我希望select(filter)获取除“2016-11-17 15:20:58.3,26,0,false”之外的所有元素

我需要使用每个元素的第3个和第4个子元素...通过filtereing on(伪代码):

_3!= 0 OR _4 == true

这两个谓词在过滤器中运行良好:

scala> testme4.filter(_._3 != 0 ) 
res16: Array[(java.sql.Timestamp, Int, Int, Boolean)] 
   = Array((2016-11-17 15:18:50.47,13,-8,false),
           (2016-11-17 15:18:51.37,21,-1,false),
           (2016-11-17 15:18:51.37,22,-1,false), 
           (2016-11-17 15:18:51.86,23,-1,false), 
           (2016-11-17 15:18:52.3,24,22,false), 
           (2016-11-17 15:18:52.37,2,-2,false), 
           (2016-11-17 15:18:54.2,4,-1,false), 
           (2016-11-17 15:18:54.2,5,-7,false), 
           (2016-11-17 15:20:57.27,12,-4,false), 
           (2016-11-17 15:20:57.67,16,-1,false), 
           (2016-11-17 15:20:57.67,17,-9,false)
       )

或..

scala> testme4.filter(_._4) 
res17: Array[(java.sql.Timestamp, Int, Int, Boolean)] 
        = Array((2016-11-17 15:20:59.35,26,0,true))

但如果我尝试将它们与逻辑运算符组合,我会收到错误:

scala> testme4.filter(_._3 != 0 || _._4) 
<console>:38: error: missing parameter type for expanded function ((x$1, x$2) => x$1._3.$bang$eq(0).$bar$bar(x$2._4))
   testme4.filter(_._3 != 0 || _._4)

有没有人知道为什么会出现这种错误?以及如何使用过滤器实现简单的逻辑操作?

非常感谢提前

1 个答案:

答案 0 :(得分:0)

您应该使用short

对于testme4.filter(i => i._3 != 0 || i._4),它会导致编译器混淆推断第二种类型。当编译器抛出时,编译器正在尝试转换:

_._3 != 0 || _._4

_._3 != 0 || _._4

对于((x$1, x$2) => x$1._3.$bang$eq(0).$bar$bar(x$2._4)) 编译器无法推断出这一点,因此抛出了编译器错误