我对Scala很新。
我想实现一个通用矩阵类“class Matrix [T]”。对T的唯一约束应该是T应该实现“+”和“*”方法/函数。我该怎么做呢?
例如,我希望能够同时使用Int,Double和我自己定义的类型,例如复杂的
我正在思考一些事情:
class Matrix[T <: MatrixElement[T]](data: Array[Array[T]]) {
def *(that: Matrix) = ..// code that uses "+" and "*" on the elements
}
abstract class MatrixElement[T] {
def +(that: T): T
def *(that: T): T
}
implicit object DoubleMatrixElement extends MatrixElement[Double]{
def +(that: Double): Double = this + that
def *(that: Double): Double = this * that
}
implicit object ComplexMatrixElement extends MatrixElement[Complex]{
def +(that: Complex): Complex = this + that
def *(that: Complex): Complex = this * that
}
所有类型检查但我仍然无法实例化矩阵。我错过了隐式构造函数吗?我该怎么做呢?或者我的方法完全错了?
提前致谢 特勒尔斯
答案 0 :(得分:4)
您可以将Numeric用于Scala 2.8。它是描述here。它将取代MatrixElement及其实现:
class Matrix[T : Numeric](data: Array[Array[T]]) {
def *(that: Matrix[T]) = //
}
答案 1 :(得分:4)
终于找到了答案:-)我想我在第一次尝试时并没有那么远。 在这里:(为scala 2.8编写)
trait MatrixElement[T] {
def +(that: T): T
def *(that: T): T
}
object MatrixElement {
implicit def intToMatrixElement(x : Int) = new MatrixElement[Int] {
def +(y : Int) = x + y
def *(y : Int) = x * y
}
implicit def doubleToMatrixElement(x : Double) = new MatrixElement[Double] {
def +(y : Double) = x + y
def *(y : Double) = x * y
}
implicit def complexToMatrixElement(x : Complex) = new MatrixElement[Complex] {
def +(y : Complex) = x + y
def *(y : Complex) = x * y
}
}
class Matrix[T <% MatrixElement[T] : ClassManifest ](d: Array[Array[T]]) {
def *(that: Matrix) = ..// code that uses "+" and "*" on the elements
}
现在我可以做类似的事情:
scala> new Matrix(Array(Array(1,0),Array(0,1)))
res0: Matrix[Int] =
1 0
0 1
scala> new Matrix(Array(Array(new Complex(0),new Complex(1)),Array(new Complex(1),new Complex(0))))
res9: Matrix[Complex] =
(0.0,0.0i) (1.0,0.0i)
(1.0,0.0i) (0.0,0.0i)
答案 2 :(得分:2)
以下是Numeric
解决方案的外观:
// ': Numeric[T]' adds an implicit parameter to the constructor,
// which allows T to be used in arithmetic expressions.
class Matrix[T: Numeric](val data: Array[Array[T]]) {
def *(that: Matrix[T]) = {
val nt = implicitly[Numeric[T]]
import nt._ // This imports an Implicit View to allow operator syntax
this.data(0)(0) * that.data(0)(0)
// etc
}
}