Math 重载BigDecimal';Groovy中的s乘法方法

Math 重载BigDecimal';Groovy中的s乘法方法,math,matrix,groovy,operator-overloading,Math,Matrix,Groovy,Operator Overloading,我在Groovy中创建了一个类Matrix,并重载了multiply()函数,这样我就可以轻松编写如下内容: Matrix m1 = [[1.0, 0.0],[0.0,1.0]] Matrix m2 = m1 * 2.0 Matrix m3 = m1 * m2 Matrix m4 = m1 * [[5.0],[10.0]] 但现在,让我们假设我写: Matrix m5 = 2.0 * m1 Matrix m6 = [[5.0,10.0]] * m1 这两行产生错误,因为类BigDecimal

我在Groovy中创建了一个类
Matrix
,并重载了
multiply()
函数,这样我就可以轻松编写如下内容:

Matrix m1 = [[1.0, 0.0],[0.0,1.0]]
Matrix m2 = m1 * 2.0
Matrix m3 = m1 * m2
Matrix m4 = m1 * [[5.0],[10.0]]
但现在,让我们假设我写:

Matrix m5 = 2.0 * m1
Matrix m6 = [[5.0,10.0]] * m1
这两行产生错误,因为类
BigDecimal
ArrayList
不能与
矩阵相乘


有没有办法为这些类重载
multiply()
?(我知道我可以扩展这两个类,但是有没有办法告诉Groovy在编译代码时使用扩展类?

您可以在
BigDecimal
ArrayList
中重载
multiply()
方法。扩展类不会像您希望的那样工作,因为Groovy不会从
BigDecimal
List
文本创建子类的实例

我的第一个建议是只使用
Matrix
实例是
multiply()
方法的接收者的语法。矩阵。乘法(无论什么)。这是为了避免创建大量重复的
multiply()
实现。例如,矩阵乘法(BigInteger)和BigInteger.乘法(矩阵)

一个例子 不管怎样,下面是一个如何向
BigDecimal
List
添加矩阵数学方法的示例:

Matrix m1 = [[1.0, 0.0],[0.0,1.0]]
def m2 = m1 * 2.0
def m3 = m1 * m2

use(MatrixMath) {
    def m4 = 2.0 * m1
    def m5 = [[5.0,10.0]] * m1
}

/*
 * IMPORTANT: This is a dummy Matrix implementation.
 * I was bored to death during this particular
 * math lesson.
 * In other words, the matrix math is all made up!
 */
@groovy.transform.TupleConstructor
class Matrix {
    List<List> matrix

    Matrix multiply(BigDecimal number) {
        matrix*.collect { it * 2 }
    }

    Matrix multiply(Matrix other) {
        (matrix + other.matrix)
            .transpose()
            .flatten()
            .collate(2)
            .collect { it[0] * it[1] }
            .collate(2)
    }
}

class MatrixMath {
    static Matrix multiply(BigDecimal number, Matrix matrix) {
        matrix * number
    }

    static Matrix multiply(List list, Matrix matrix) {
        matrix * (list as Matrix)
    }
}
矩阵m1=[[1.0,0.0],[0.0,1.0]] def m2=m1*2.0 def m3=m1*m2 使用(MatrixMath){ def m4=2.0*m1 def m5=[[5.0,10.0]]*m1 } /* *重要提示:这是一个虚拟矩阵实现。 *在这个特殊的日子里,我烦死了 *数学课。 *换句话说,矩阵的数学都是虚构的! */ @groovy.transform.TupleConstructor 类矩阵{ 列表矩阵 矩阵乘法(大十进制数){ 矩阵*.collect{it*2} } 矩阵乘法(矩阵其他){ (矩阵+其他矩阵) .transpose() .flatte() .核对(2) .collect{it[0]*it[1]} .核对(2) } } 类矩阵路径{ 静态矩阵乘法(大十进制数,矩阵){ 矩阵*数 } 静态矩阵乘法(列表、矩阵){ 矩阵*(列表为矩阵) } }
本例使用Groovy类别。我选择了一个类别,将multiply()实现放在一个类中

如果矩阵只不过是一个
列表
,请注意,使用这种方法实际上可以摆脱
矩阵
类。相反,您可以将所有的
multiply()
实现放入
MatrixMath
类别,并使用
列表作为矩阵