I am very new to Scala.
I want to implement a generic matrix class "class Matrix[T]". The only constraint on T should be that T should implement a "+" and a "*" mothod/function. How do I go about doing this?
For example I want to be able to use both Int, Double, and my own defined types e.g. Complex
I was thinking something along the lines:
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
}
Everything type checks but I still can't instantiate a matrix. Am I missing an implicit constructor? How would I go about making that? Or am I completely wrong about my method?
Thanks in advance Troels
You can use Numeric for Scala 2.8 for that. It is describe here. It would replace MatrixElement and its implementations:
class Matrix[T : Numeric](data: Array[Array[T]]) {
def *(that: Matrix[T]) = //
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With