import scala.collection.generic.CanBuildFrom
import scala.collection.GenTraversable
import scala.collection.GenTraversableLike
def shiftIndex[T, Repr](seq: GenTraversableLike[(T, Int), Repr], amount: Int)(
implicit bf: CanBuildFrom[Repr, (T, Int), Repr]) = {
seq.map { case (value, integer) => (value, integer + amount) }
}
shiftIndex(List(("a", 1), ("b", 2)), 3) // List((a,4), (b,5))
shiftIndex(Set(("a", 1), ("b", 2)), 3) // Set((a,4), (b,5))
shiftIndex(Map(("a", 1), ("b", 2)), 3) // Map(a -> 4, b -> 5)
虽然我可能会推荐一个更好看、更通用的解决方案。在这里,我丰富了 GenTraversable,以便对的所有可遍历对象都有一个方法,该方法mapVals
将一个函数应用于该对的第二部分,并具有与运行它的对象相同的返回类型:
class EnrichedWithMapVals[T, U, Repr](seq: GenTraversableLike[(T, U), Repr]) {
def mapVals[R, That](f: U => R)(implicit bf: CanBuildFrom[Repr, (T, R), That]) = {
seq.map { case (x, y) => (x, f(y)) }
}
}
implicit def enrichWithMapVals[T, U, Repr](self: GenTraversableLike[(T, U), Repr]) = new EnrichedWithMapVals(self)
List(("a", 1), ("b", 2)).mapVals(_ + 3) // List((a,4), (b,5))
Set(("a", 1), ("b", 2)).mapVals(_ + 3) // Set((a,4), (b,5))
Map(("a", 1), ("b", 2)).mapVals(_ + 3) // Map(a -> 4, b -> 5)