[英]map a function on a sequence of tuples
Given the following code : 给出以下代码:
def map1[A,B,C](s: Seq[(A, B)])(f: A => C) : Seq[(C, B)] =
s.map { case (a, b) => (f(a), b) }
Is there a better way to code that (maybe something exist in scalaz) ? 有没有更好的编码方式(也许在scalaz中存在)?
Can you help me to find a better name ? 你能帮我找到一个更好的名字吗?
Is there a more generic abstraction to use ( Iterable
, TraversableOnce
) ? 是否有更通用的抽象(
Iterable
, TraversableOnce
)使用?
You could define an extension method: 您可以定义一个扩展方法:
import scala.collection.GenTraversable
import scala.collection.GenTraversableLike
import scala.collection.generic.CanBuildFrom
implicit class WithMapKeys[A, B, Repr](val self: GenTraversableLike[(A, B), Repr]) extends AnyVal {
def mapKeys[C, That](f: A => C)(implicit bf: CanBuildFrom[Repr, (C, B), That]) = {
self.map(x => f(x._1) -> x._2)
}
}
Then: 然后:
Vector(1->"a", 2->"b").mapKeys(_+2)
// res0: scala.collection.immutable.Vector[(Int, String)] = Vector((3,a), (4,b))
Map(1->"a", 2->"b").mapKeys(_+2)
// res1: scala.collection.immutable.Map[Int,String] = Map(3 -> a, 4 -> b)
Similarly for Iterator: 对于Iterator同样:
implicit class WithMapKeysItr[A, B](val self: Iterator[(A, B)]) extends AnyVal {
def mapKeys[C](f: A => C): Iterator[(C, B)] = {
self.map(x => f(x._1) -> x._2)
}
}
val i2 = Iterator(1->"a", 2->"b").mapKeys(_+2)
// i2: Iterator[(Int, String)] = non-empty iterator
i2.toVector
// res2: Vector[(Int, String)] = Vector((3,a), (4,b))
val to: TraversableOnce[(Int, String)] = Vector(1->"a", 2->"b")
val i3 = to.toIterator.mapKeys(_+2)
// i3: Iterator[(Int, String)] = non-empty iterator
i3.toMap
// res3: scala.collection.immutable.Map[Int,String] = Map(3 -> a, 4 -> b)
Shapeless could make it a little more prettier (without pattern matching): Shapeless可以使其更漂亮(没有模式匹配):
import shapeless.syntax.std.tuple._
def mapKeys[A,B,C](s: Seq[(A, B)])(f: A => C) : Seq[(C, B)] =
s.map(x => x.updatedAt(0, f(x.head)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.