我怎样才能制作矩阵+ Scala 中的运算符?
我制作了矩阵类和 mop 方法(它以二元运算符作为参数并启用每个元素操作),但我无法使用 mop 方法制作 + 运算符。
val matA = new Matrix[Int](List(1 :: 2 :: 3 :: Nil, 4 :: 5 :: 6 :: Nil))
val matB = new Matrix[Int](List(7 :: 8 :: 9 :: Nil, 10 :: 11 :: 12 :: Nil))
val matC =matA. mop( matB) (_ + _) //can work
def +(that: Matrix[T]) = this.mop(that)(_ + _) //can't work
val matC = matA + matB
//class definition
type F[T] = (T, T) => T
type M[T] = List[List[T]]
class Matrix[T](val elms: M[T]) {
override def toString()= (this.elms map (_.mkString("[", ",", "]"))).mkString("\n")
def mop(that: Matrix[T])(op: F[T]): Matrix[T] = new Matrix[T](((this.elms zip that.elms).map(t => ((t._1 zip t._2)).map(s => op(s._1, s._2)))))
// def +(that: Matrix[T]) = this.mop(that)(_ + _)
}
I made matrix class and mop method (it takes binary operator as argument and enables each elements operation),but Ican't make + operator with mop method.
val matA = new Matrix[Int](List(1 :: 2 :: 3 :: Nil, 4 :: 5 :: 6 :: Nil))
val matB = new Matrix[Int](List(7 :: 8 :: 9 :: Nil, 10 :: 11 :: 12 :: Nil))
val matC =matA. mop( matB) (_ + _) //can work
def +(that: Matrix[T]) = this.mop(that)(_ + _) //can't work
val matC = matA + matB
//class definition
type F[T] = (T, T) => T
type M[T] = List[List[T]]
class Matrix[T](val elms: M[T]) {
override def toString()= (this.elms map (_.mkString("[", ",", "]"))).mkString("\n")
def mop(that: Matrix[T])(op: F[T]): Matrix[T] = new Matrix[T](((this.elms zip that.elms).map(t => ((t._1 zip t._2)).map(s => op(s._1, s._2)))))
// def +(that: Matrix[T]) = this.mop(that)(_ + _)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是
T
可能没有定义加法。因此,当您有一个特定的矩阵(整数之一)时,mop
就知道要做什么。但通用代码不起作用。您可以使用隐式
Numeric
为T
提供数字运算(如果存在):The problem is that
T
might not have addition defined. So when you have a particular matrix--one of Ints--thenmop
knows what to do. But the generic code doesn't work.You could use an implicit
Numeric
to provide numeric operations forT
(if they exist):