2011-03-10 77 views
0

我做了矩陣類和拖把方法(它採用二元運算符作爲參數,並啓用每個元素操作),但我不能用拖把方法使+運算符。如何在Scala中創建矩陣+運算符?

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)(_ + _) 

} 

回答

2

問題是T可能沒有添加定義。所以當你有一個特定的矩陣 - 一個Ints - 然後mop知道該怎麼做。但通用代碼不起作用。

你可以使用隱式NumericT提供數字操作(如果存在的話):

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)(_ + _) 
} 
+0

我不知道如何使用數字,但現在我明白你it.thank。 – mnru 2011-03-12 06:34:22