你不必把整个名单除了我猜。 (只有等到元素被发现)
def replaceFirst[A](a : List[A], repl : A, replwith : A) : List[A] = a match {
case Nil => Nil
case head :: tail => if(head == repl) replwith :: tail else head :: replaceFirst(tail, repl, replwith)
}
呼叫例如:
replaceFirst(List(('a', 1), ('b', 1), ('c', 1), ('b', 1)), ('b', 1), ('b', 2))
结果:
List((a,1), (b,2), (c,1), (b,1))
与部分功能和implicits(这看起来更像是一种你mapFirst):
implicit class MyRichList[A](val list: List[A]) {
def mapFirst(func: PartialFunction[A, A]) = {
def mapFirst2[A](a: List[A], func: PartialFunction[A, A]): List[A] = a match {
case Nil => Nil
case head :: tail => if (func.isDefinedAt(head)) func.apply(head) :: tail else head :: mapFirst2(tail, func)
}
mapFirst2(list, func)
}
}
并像这样使用它:
List(('a', 1), ('b', 1), ('c', 1), ('b', 1)).mapFirst {case ('b', num) => ('b', num + 1)}
恐怕这个解决方案浪费了堆栈。在大列表中,解决方案将抛出'StackOverflowException'。最好将解决方案更改为'@ tailrec'。通常这是通过函数内部的'ListBuffer [T]'参数完成的。 –