0

我编写了以下基于模式匹配的函数:

def replacingElem(lines: List[String], last10: String): List[String] = 
{
  if (lines.isEmpty) Nil else {
    val row = lines.head.split("[ \t]+")
    row(0).toInt match {
      case 10 => lines.head :: replacingElem(lines.tail, row(1))
      case 15 => (row(0) + " " + last10 + " " + row(2) + " " + row(3)) :: replacingElem(lines.tail, last10)
      case _ => lines.head :: replacingElem(lines.tail, last10)
    }
  }
}

我的目标是使整数 10 和 15 可调,并将它们作为函数的参数。我做了以下修改:

def replaceIndex(lines: List[String], last10: String,a:Int,b:Int): List[String] = {
  if (lines.isEmpty) Nil else {
    val row = lines.head.split("[ \t]+")
    row(0).toInt match {
      case a => lines.head :: replaceIndex(lines.tail, row(1),a,b)
      case b => (row(0) + " " + last10 + " " + row(2) + " " + row(3)) :: replaceIndex(lines.tail, last10,a,b)
      case _ => lines.head :: replaceIndex(lines.tail, last10,a,b)
    }
  }
}

但我得到了编译错误。

4

1 回答 1

5

背部抽动...

case `a` => ...
case `b` => ...

...告诉编译器,“不要在这里创建新变量,使用这些现有变量中的值。”

另一种选择是以大写字母开头的变量名。

def replaceIndex(lines:List[String], last10:String, A:Int, B:Int):List[String]=...

但我更喜欢 back-tics 解决方案。

于 2018-05-02T05:38:57.903 回答