将特定的地图方法添加到集合/仿函数

时间:2016-04-02 14:34:10

标签: scala functor

所以我有一个Vec2课程:

class Vec2(val x: Double, val y: Double)
{
  def +(other: Vec2): Vec2 = Vec2(x + other.x, y + other.y)   
  def -(other: Vec2): Vec2 = Vec2(x - other.x, y - other.y)
  def *(factor: Double): Vec2 = Vec2(x * factor, y * factor)
  def /(divisor: Double): Vec2 = Vec2(x / divisor, y / divisor)
  //Other methods omitted but you get the idea
}

我经常使用这个类,并且我在集合中使用它很多,所以我想要.map(_ + other).map(_ * factor)等的简写方法。我还想为addMultAll添加方法(第二个:Vec2,因子:Double)和multAddAll(因子:Double,第二个:Vec2),我认为它会像显式方法一样更清晰,更安全。

所以我为隐含的选择了可遍历的类。这是我可以使用的最好/最普通的课程吗?我已经从scala源代码中修改并修改了map方法。以下代码是否正确?它会没有问题吗?

object Vec2
{   
  import collection.mutable.{ Builder }
  import scala.collection._
  implicit class ImpVec2Class[+Repr](travLike: TraversableLike[Vec2, Repr])
  {
    def +++ [That](offset: Vec2)(implicit bf: generic.CanBuildFrom[Repr, Vec2, That]): That =
    {
       def builder =
       { // extracted to keep method size under 35 bytes, so that it can be JIT-inlined
          val b = bf(travLike.repr)
          b.sizeHint(travLike)
          b
       }
       val b = builder
       for (x <- travLike) b += x + offset
       b.result
    }
  }
}

如果我想要缩短方法,或者Scalaz / CATS是否已包含它们,我是否需要对Double上的map方法执行此操作?

1 个答案:

答案 0 :(得分:0)

好的,我会发布这个作为答案,因为它略有改善。我已删除方法上的[That]类型参数。我还为Array [Vec2]添加了一个暗示,因为Array不会从Scala集合特征中继承。

object Vec2
{   
  import collection.mutable.{ Builder }
  import scala.collection._
  implicit class ImpVec2Traversible[Repr](travLike: TraversableLike[Vec2, Repr])
  {
    def +++ (offset: Vec2)(implicit bf: generic.CanBuildFrom[Repr, Vec2, Repr]): Repr =
    {
     def builder =
     { // extracted to keep method size under 35 bytes, so that it can be JIT-inlined
        val b = bf(travLike.repr)
        b.sizeHint(travLike)
        b
     }
     val b = builder
     for (x <- travLike) b += x + offset
     b.result
  }
}
  implicit class ImpVec2Array(arr: Array[Vec2])
  {
    def +++ (offset: Vec2): Array[Vec2] = arr.map(_ + offset)
  }
}