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)(_ + _)
}
The problem is that T
might not have addition defined. So when you have a particular matrix--one of Ints--then mop
knows what to do. But the generic code doesn't work.
You could use an implicit Numeric
to provide numeric operations for T
(if they exist):
class Matrix[T](val elms: M[T])(implicit nt: Numeric[T]) {
import nt._
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)(_ + _)
}
精彩评论