Scala模式匹配空元素重复

时间:2017-03-22 15:47:41

标签: scala pattern-matching

我有以下代码快照,带有可重复的样板,下面有大量的下划线:

    ...............
    case (a, c) =>
              (a, c.map {
                case (_, aParam, _, _, _, _, _, _, _, _, _) => aParam
              }, 
               c.map {
                case (_, _ , cParam, _, _, _, _, _, _, _, _) => cParam
              },
              c.map {
                case (_, _ , dParam, _, _, _, _, _, _, _, _) => dParam
              }
   ................
             c.map {
                case (_, _ , _, _, _, _, _, _, _, _, eParam) => eParam
              }

我想替换这个样板,但我不想使用无形或其他库。

UPD

c的类型为List [(Int,String,......,String)]

3 个答案:

答案 0 :(得分:0)

您可以使用以下内容清理代码:

case (a, c) =>
    c.map{
        case (c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11) =>
         // do whatever processing you like here for each value in the tuple above
        c2.filter(_.equals(aParam)).doStuff
        ...
    }

答案 1 :(得分:0)

case (a, c) =>
  (a, c.map(_._2).map {
    case aParam => aParam
  }, c.map(_._3).map {
    case cParam => cParam
  }, c.map(_._2).map {
    case dParam => dParam
  }, ..., c.map(_._11).map {
    case eParam => eParam
  })

这与您的代码完全相同,但我不确定aParamcParam和其他人的确切含义。

答案 2 :(得分:0)

你可能想要这样的东西:

  //########################################################
  //Old Way (If i understand ur approach correctly)
  val tup1 = (7, "apple", "ball", "Cat", "dog")
  val tup2 = (8, "w", "x", "y", "z")
  val tup3 = (9, "r1", "r2", "r3", "r4")

  var tupList: List[(Int, String, String, String, String)] = List(tup1, tup2, tup3)

  tupList.foreach(item => {
    item match {
      case (_, "apple", _, _, _) => println("apple")
      case (_, _, "x", _, _) => println("y")
      case (_, _, _, _, "r4") => println("r4")
    }
  })

  //#######################################################
  //New Way ~
  //Define your match filter like this: (key - position(0 based index)), ("apple", 1) ~ case (_, "apple", _, _, _) 
  val filter: List[(String, Int)] = List(("apple", 1), ("x", 2), ("r4", 4))

  //Now, iterate through list, convert each tuple to iterator, and check each item of tuple with
  //filter condition, i.e. item must match filter string and index e.g. ("apple", 1)
  //Also, you don't have to worry about size of list or tuple. You can create some generic method as well using this logic. 
  tupList.map(tup => {
    val iterator = tup.productIterator
    var i = 0
    while (iterator.hasNext) {
      val item = iterator.next()
      filter.map(f => {
        val filterString = f._1
        val position = f._2
        if (i == position && item == filterString) {
          println(tup) //matched.
        }
      })
      i = i + 1
    }
  })