【发布时间】:2021-05-03 16:20:42
【问题描述】:
假设我有 case class A(x: Int, s: String) 并且需要像这样使用 Map[Int, String] 更新 List[A]:
def update(as: List[A], map: Map[Int, String]): List[A] = ???
val as = List(A(1, "a"), A(2, "b"), A(3, "c"), A(4, "d"))
val map = Map(2 -> "b1", 4 -> "d1", 5 -> "e", 6 -> "f")
update(as, map) // List(A(1, "a"), A(2, "b1"), A(3, "c"), A(4, "d1"))
我这样写update:
def update(as: List[A], map: Map[Int, String]): List[A] = {
@annotation.tailrec
def loop(acc: List[A], rest: List[A], map: Map[Int, String]): List[A] = rest match {
case Nil => acc
case as => as.span(a => !map.contains(a.x)) match {
case (xs, Nil) => xs ++ acc
case (xs, y :: ys) => loop((y.copy(s = map(y.x)) +: xs) ++ acc, ys, map - y.x)
}
}
loop(Nil, as, map).reverse
}
此函数工作正常,但不是最理想的,因为当map 为空时,它会继续迭代输入列表。此外,它看起来过于复杂。你建议如何改进这个update 功能?
【问题讨论】:
标签: scala collections tail-recursion