我可以用TraversableLike.map的类似物来"pimp my library"吗?它具有很好的变体类型?

Sco*_*son 7 scala variance implicit-conversion scala-collections

假设我要像功能添加map到斯卡拉List,沿着线的东西list mapmap f,其功能适用f于每个元素list的两倍.(一个更严重的例子可能是实现并行或分布式地图,但我不想被那个方向的细节分心.)

我的第一种方法是

object MapMap {
    implicit def createFancyList[A](list: List[A]) = new Object {
        def mapmap(f: A => A): List[A] = { list map { a: A => f(f(a)) } }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在这很好用

scala> import MapMap._
import MapMap._

scala> List(1,2,3) mapmap { _ + 1 }
res1: List[Int] = List(3, 4, 5)
Run Code Online (Sandbox Code Playgroud)

当然除了这只是为ListS,而且也没有理由我们不应该想这对任何工作Traverseable,具有map功能,例如SetS或Stream秒.所以第二次尝试看起来像

object MapMap2 {
    implicit def createFancyTraversable[A](t: Traversable[A]) = new Object {
        def mapmap(f: A => A): Traversable[A] = { t map { a: A => f(f(a)) } }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是现在,当然,结果不能分配给List[A]:

scala> import MapMap2._
import MapMap2._

scala> val r: List[Int] = List(1,2,3) mapmap { _ + 1 }
<console>:9: error: type mismatch;
 found   : Traversable[Int]
 required: List[Int]
Run Code Online (Sandbox Code Playgroud)

有一些中间立场吗?我可以编写一个隐式转换,将方法添加到Traversable的所有子类,并成功返回具有该类型的对象吗?

(我猜这涉及到了解可怕的CanBuildFrom特性,甚至可能breakout!)

ret*_*nym 11

您无法对所有Traversable执行此操作,因为它们不保证map返回比Traversable更具体的内容. 见下面的更新2.

import collection.generic.CanBuildFrom
import collection.TraversableLike

class TraversableW[CC[X] <: TraversableLike[X, CC[X]], A](value: CC[A]) {
  def mapmap(f: A => A)(implicit cbf: CanBuildFrom[CC[A], A, CC[A]]): CC[A] 
      = value.map(f andThen f)
  def mapToString(implicit cbf: CanBuildFrom[CC[A], String, CC[String]]): CC[String]
      = value.map(_.toString)
}

object TraversableW {
  implicit def TraversableWTo[CC[X] <: TraversableLike[X, CC[X]], A](t: CC[A]): TraversableW[CC, A] 
      = new TraversableW[CC, A](t)
}

locally {
  import TraversableW._

  List(1).mapmap(1+)
  List(1).mapToString
  // The static type of Seq is preserved, *and* the dynamic type of List is also
  // preserved.
  assert((List(1): Seq[Int]).mapmap(1+) == List(3))
}
Run Code Online (Sandbox Code Playgroud)

更新 我添加了另一个pimped方法,mapToString以演示为什么TraversableW接受两个类型参数,而不是像Alexey的解决方案中的一个参数.该参数CC是较高的kinded类型,它表示原始集合的容器类型.第二个参数A表示原始集合的元素类型.mapToString因此,该方法能够返回具有不同元素类型的原始容器类型:CC[String.

更新2 感谢@oxbow_lakes发表评论,我已经重新思考了这一点.确实有可能直接皮条客CC[X] <: Traversable[X],TraversableLike并非严格需要.评论内联:

import collection.generic.CanBuildFrom
import collection.TraversableLike

class TraversableW[CC[X] <: Traversable[X], A](value: CC[A]) {
  /**
   * A CanBuildFromInstance based purely the target element type `Elem`
   * and the target container type `CC`. This can be converted to a
   * `CanBuildFrom[Source, Elem, CC[Elem]` for any type `Source` by
   * `collection.breakOut`.
   */
  type CanBuildTo[Elem, CC[X]] = CanBuildFrom[Nothing, Elem, CC[Elem]]

  /**
   * `value` is _only_ known to be a `Traversable[A]`. This in turn
   * turn extends `TraversableLike[A, Traversable[A]]`. The signature
   * of `TraversableLike#map` requires an implicit `CanBuildFrom[Traversable[A], B, That]`,
   * specifically in the call below `CanBuildFrom[Traversable[A], A CC[A]`.
   *
   * Essentially, the specific type of the source collection is not known in the signature
   * of `map`.
   *
   * This cannot be directly found instead we look up a `CanBuildTo[A, CC[A]]` and
   * convert it with `collection.breakOut`
   *
   * In the first example that referenced `TraversableLike[A, CC[A]]`, `map` required a
   * `CanBuildFrom[CC[A], A, CC[A]]` which could be found.
   */
  def mapmap(f: A => A)(implicit cbf: CanBuildTo[A, CC]): CC[A]
      = value.map[A, CC[A]](f andThen f)(collection.breakOut)
  def mapToString(implicit cbf: CanBuildTo[String, CC]): CC[String]
      = value.map[String, CC[String]](_.toString)(collection.breakOut)
}

object TraversableW {
  implicit def TraversableWTo[CC[X] <: Traversable[X], A](t: CC[A]): TraversableW[CC, A]
      = new TraversableW[CC, A](t)
}

locally {
  import TraversableW._

  assert((List(1)).mapmap(1+) == List(3))

  // The static type of `Seq` has been preserved, but the dynamic type of `List` was lost.
  // This is a penalty for using `collection.breakOut`. 
  assert((List(1): Seq[Int]).mapmap(1+) == Seq(3))   
}
Run Code Online (Sandbox Code Playgroud)

有什么不同?我们不得不使用collection.breakOut,因为我们无法从单纯的特定收集子类型中恢复Traversable[A].

def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
  val b = bf(repr)
  b.sizeHint(this) 
  for (x <- this) b += f(x)
  b.result
}
Run Code Online (Sandbox Code Playgroud)

Builder b初始化与原来的集合,这是通过保持动态类型的机制map.然而,我们通过类型论证CanBuildFrom否认了对From的所有知识Nothing.你可以做的Nothing只是忽略它,这正是breakOut:

def breakOut[From, T, To](implicit b : CanBuildFrom[Nothing, T, To]) =
  new CanBuildFrom[From, T, To] {
    def apply(from: From) = b.apply();
    def apply() = b.apply()
  }
Run Code Online (Sandbox Code Playgroud)

我们不能打电话b.apply(from),只能打电话给你def foo(a: Nothing) = 0.

  • 我在Scalaz中采用了稍微不同的方法,这有点强大:http://github.com/scalaz/scalaz/blob/master/core/src/main/scala/scalaz/CanBuildAnySelf.scala#L24 http:/ /github.com/scalaz/scalaz/blob/master/core/src/main/scala/scalaz/Functor.scala#L28 (2认同)

Ale*_*nov 5

一般来说,当你想用同一类型返回对象,你需要TraversableLike(IterableLike,SeqLike,等)代替Traversable.这是我可以提出的最通用的版本(单独的FancyTraversable类是为了避免推断结构类型和反射命中):

class FancyTraversable[A, S <: TraversableLike[A, S]](t: S) {
  def mapmap(f: A => A)(implicit bf: CanBuildFrom[S,A,S]): S = { t map { a: A => f(f(a)) } }
}

implicit def createFancyTraversable[A, S <: TraversableLike[A, S]](t: S): FancyTraversable[A, S] = new FancyTraversable(t)
Run Code Online (Sandbox Code Playgroud)