【问题标题】:Overload BigDecimal's multiply method in Groovy在 Groovy 中重载 BigDecimal 的乘法方法
【发布时间】:2015-12-08 20:49:09
【问题描述】:

我在 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

这两行会产生错误,因为 BigDecimalArrayList 类不能乘以 Matrix

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

【问题讨论】:

    标签: math matrix groovy operator-overloading


    【解决方案1】:

    您可以在BigDecimalArrayList 中重载multiply() 方法。扩展类不会按您的意愿工作,因为 Groovy 不会从 BigDecimalList 文字创建子类的实例。

    我的第一个建议是简单地坚持 Matrix 实例是 multiply() 方法的接收者的语法。例如:matrix.multiply(whatever)。这是为了避免创建一堆重复的multiply() 实现。前任。 Matrix.multiply(BigInteger)BigInteger.multiply(Matrix).

    一个例子

    不管怎样,这里有一个如何将矩阵数学方法添加到 BigDecimalList 的示例:

    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)
        }
    }
    

    此示例使用 Groovy 类别。我选择了一个 Category 来将 multiply() 实现放在一个类中。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-06
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-15
      相关资源
      最近更新 更多