根据任意数量的选项过滤集合

时间:2016-08-06 21:11:36

标签: scala

如何重构以下Scala函数以使用惯用最佳实践?

  def getFilteredList(ids: Seq[Int], 
      idsMustBeInThisListIfItExists: Option[Seq[Int]], 
      idsMustAlsoBeInThisListIfItExists: Option[Seq[Int]]): Seq[Int] = {

    var output = ids

    if (idsMustBeInThisListIfItExists.isDefined) {
      output = output.intersect(idsMustBeInThisListIfItExists.get)
    }
    if (idsMustAlsoBeInThisListIfItExists.isDefined) {
      output = output.intersect(idsMustAlsoBeInThisListIfItExists.get)
    }

    output 
  }

预期IO:

val ids = Seq(1,2,3,4,5)
val output1 = getFilteredList(ids, None, Some(Seq(3,5))) // 3, 5
val output2 = getFilteredList(ids, None, None) // 1,2,3,4,5
val output3 = getFilteredList(ids, Some(Seq(1,2)), None) // 1,2
val output4 = getFilteredList(ids, Some(Seq(1)), Some(Seq(5))) // 1,5

感谢您的时间。

3 个答案:

答案 0 :(得分:2)

这是一种简单的方法:

R version 3.3.1 (2016-06-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
caret_6.0-71

答案 1 :(得分:2)

另一种没有理解和暗示的方式:

def getFilteredList(ids: Seq[Int],
                  idsMustBeInThisListIfItExists: Option[Seq[Int]],
                  idsMustAlsoBeInThisListIfItExists: Option[Seq[Int]]): Seq[Int] = {

  val output1 = ids.intersect(idsMustBeInThisListIfItExists.getOrElse(ids))
  val output2 = output1.intersect(idsMustAlsoBeInThisListIfItExists.getOrElse(output1))

  output2
}

答案 2 :(得分:1)

另一种类似的方式,没有暗示。

def getFilteredList[A](ids: Seq[A],
                       idsMustBeInThisListIfItExists: Option[Seq[A]],
                       idsMustAlsoBeInThisListIfItExists: Option[Seq[A]]): Seq[A] = {
  val  a = intersect(Some(ids), idsMustBeInThisListIfItExists)(ids)
  val  b = intersect(Some(a), idsMustAlsoBeInThisListIfItExists)(a)
  b
}

def intersect[A](ma: Option[Seq[A]], mb: Option[Seq[A]])(default: Seq[A]) = {
  (for {
     a <- ma
     b <- mb
   } yield {
     a.intersect(b)
   }).getOrElse(default)
}