Scala:对泛型类类型的约束
我对 Scala 很陌生。
我想实现一个通用矩阵类“class Matrix[T]”。对 T 的唯一约束应该是 T 应该实现“+”和“*”方法/函数。我该怎么做呢?
例如,我希望能够使用 Int、Double 和我自己定义的类型,例如 Complex
我正在考虑这样的事情:
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
}
一切类型检查,但我仍然无法实例化矩阵。我缺少隐式构造函数吗?我该怎么做呢?或者我的方法完全错误?
提前致谢 特罗尔斯
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 Scala 2.8 的 Numeric那。 此处描述 。它将取代 MatrixElement 及其实现:
You can use Numeric for Scala 2.8 for that. It is describe here. It would replace MatrixElement and its implementations:
终于找到了答案:-)我想我的第一次尝试并没有那么遥远。
就这样:(为 scala 2.8 编写)
现在我可以做类似的事情:
Finally found the answer :-) I think I wasn't that far off in my first try.
Here it goes: (written for scala 2.8)
Now I can do stuff like:
Numeric
解决方案如下所示:Here's how the
Numeric
solution would look: