我希望它具有性能特征,并包括Array [Double]的大多数方法,但具有其他扩展方法,例如dotProduct(),+,-等。我可以编写其他扩展方法,但需要帮助关于现有特征的实现以及获得类似Array的性能所需的措施。
class Vec(private val content:Array[Double]) extends WrappedArray[Double] {
/* Trait implementation methods - incomplete */
def array = content
def apply(i:Int) = content(i)
def length = content.length
def update(i:Int, v:Double) = content.update(i, v)
def elemTag = ???
/* Example extension methods */
def plus(that:Vec) = Vec(this.indices.map{ i => this(i) + that(i)})
def elementProduct(that:Vec) = Vec(this.indices.map{ i => this(i) * that(i)})
def sum = content.sum
def dotProduct(that:Vec) = elementProduct(that).sum
}
object Vec {
def apply(seq:IndexedSeq[Double]) = new Vec(seq.toArray)
}
答案 0 :(得分:1)
如果您只希望Array[Double]
有一些新方法,那么最好的方法是定义一个implicit class来提供其他方法。像这样:
implicit class ArrayOps(vec: Array[Double]) {
def plus(that: Array[Double]): Array[Double] =
vec.indices.map(i => vec(i) + that(i))(collection.breakOut)
def elementProduct(that: Array[Double]): Array[Double] =
vec.indices.map(i => vec(i)*that(i))(collection.breakOut)
def dotProduct(that: Array[Double]): Double =
(vec elementProduct that).sum
}
然后您可以在任何plus
上调用elementProduct
,dotProduct
和Array[Double]
,它将从implicit class
执行适当的操作。