可能重复:
你能在haskell中超载吗?
你能实现一个可以在两个矩阵上工作的Matrix类和*运算符吗?:
scala> val x = Matrix(3, 1,2,3,4,5,6)
x: Matrix =
[1.0, 2.0, 3.0]
[4.0, 5.0, 6.0]
scala> x*x.transpose
res0: Matrix =
[14.0, 32.0]
[32.0, 77.0]
Run Code Online (Sandbox Code Playgroud)
所以人们不会说这很难,这就是Scala的实现(由Jonathan Merritt提供):
class Matrix(els: List[List[Double]]) {
/** elements of the matrix, stored as a list of
its rows */
val elements: List[List[Double]] = els
def nRows: Int = elements.length
def nCols: Int = if (elements.isEmpty) 0
else elements.head.length
/** all rows of the matrix must have the same
number of columns …Run Code Online (Sandbox Code Playgroud)