43

'map' 保留了元素的数量,因此在元组上使用它似乎是明智的。

到目前为止我的尝试:

scala> (3,4).map(_*2)    
error: value map is not a member of (Int, Int)
       (3,4).map(_*2)
             ^
scala> (3,4).productIterator.map(_*2)
error: value * is not a member of Any
       (3,4).productIterator.map(_*2)
                                  ^
scala> (3,4).productIterator.map(_.asInstanceOf[Int]*2)
res4: Iterator[Int] = non-empty iterator

scala> (3,4).productIterator.map(_.asInstanceOf[Int]*2).toList
res5: List[Int] = List(6, 8)

它看起来很痛苦......而且我什至还没有开始尝试将它转换回元组。
我做错了吗?图书馆可以改进吗?

4

3 回答 3

35

一般来说,一个元组的元素类型是不一样的,所以 map 没有意义。不过,您可以定义一个函数来处理特殊情况:

scala> def map[A, B](as: (A, A))(f: A => B) = 
     as match { case (a1, a2) => (f(a1), f(a2)) } 
map: [A,B](as: (A, A))(f: (A) => B)(B, B)

scala> val p = (1, 2)    
p: (Int, Int) = (1,2)

scala> map(p){ _ * 2 }
res1: (Int, Int) = (2,4)

您可以使用 Pimp My Library 模式将其称为p.map(_ * 2).

更新

即使元素的类型不相同,Tuple2[A, B]也是一个Bifunctor,它可以与bimap操作进行映射。

scala> import scalaz._
import scalaz._

scala> import Scalaz._
import Scalaz._

scala> val f = (_: Int) * 2
f: (Int) => Int = <function1>

scala> val g = (_: String) * 2
g: (String) => String = <function1>

scala> f <-: (1, "1") :-> g
res12: (Int, String) = (2,11)

更新 2

http://gist.github.com/454818

于 2010-02-26T07:11:31.790 回答
29

shapeless通过中间HList表示支持映射和折叠元组,

示例 REPL 会话,

scala> import shapeless._ ; import Tuples._
import shapeless._
import Tuples._

scala> object double extends (Int -> Int) (_*2)
defined module double

scala> (3, 4).hlisted.map(double).tupled
res0: (Int, Int) = (6,8)

如果元组的元素具有不同的类型,您可以使用具有特定类型情况的多态函数进行映射,

scala> object frob extends Poly1 {
     |   implicit def caseInt     = at[Int](_*2)
     |   implicit def caseString  = at[String]("!"+_+"!")
     |   implicit def caseBoolean = at[Boolean](!_)
     | }
defined module frob

scala> (23, "foo", false, "bar", 13).hlisted.map(frob).tupled
res1: (Int, String, Boolean, String, Int) = (46,!foo!,true,!bar!,26)

更新

从 shapeless 2.0.0-M1开始,直接支持对元组的映射。上面的例子现在看起来像这样,

scala> import shapeless._, poly._, syntax.std.tuple._
import shapeless._
import poly._
import syntax.std.tuple._

scala> object double extends (Int -> Int) (_*2)
defined module double

scala> (3, 4) map double
res0: (Int, Int) = (6,8)

scala> object frob extends Poly1 {
     |   implicit def caseInt     = at[Int](_*2)
     |   implicit def caseString  = at[String]("!"+_+"!")
     |   implicit def caseBoolean = at[Boolean](!_)
     | }
defined module frob

scala> (23, "foo", false, "bar", 13) map frob
res1: (Int, String, Boolean, String, Int) = (46,!foo!,true,!bar!,26)
于 2012-05-07T18:56:00.597 回答
1

map 函数获取一个A => B并返回F[B]

def map[A, B](f: A => B) : F[B]

正如retronym 写的Tuple2[A, B] 是一个Bifunctor,所以你可以在scalaz 或cats 中寻找bimap 函数。
bimap 是一个映射元组两边的函数:

def bimap[A, B, C, D](fa: A => C, fb: B => D): Tuple2[C, D]

因为 Tuple[A, B] 包含 2 个值,并且只能映射一个值(按照约定为右值),所以您可以只为左侧返回相同的值并使用 right 函数映射元组的右值.

(3, 4).bimap(identity, _ * 2)
于 2018-12-14T19:23:32.493 回答