在一系列元组上映射函数

时间:2015-03-06 22:41:19

标签: scala collections

给出以下代码:

def map1[A,B,C](s: Seq[(A, B)])(f: A => C) : Seq[(C, B)] = 
  s.map { case (a, b) => (f(a), b) }

有没有更好的方法来编写代码(可能是scalaz中存在的东西)?

你能帮我找一个更好的名字吗?

是否有更通用的抽象使用(IterableTraversableOnce)?

2 个答案:

答案 0 :(得分:3)

您可以定义扩展方法:

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)
  }
}

然后:

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)

类似于迭代器:

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)

答案 1 :(得分:1)

无形可以使它更漂亮(没有模式匹配):

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)))