From 3576ddaf317418be793f8516afd2f3d67a408615 Mon Sep 17 00:00:00 2001 From: Alexander Nozik Date: Sat, 25 Aug 2018 21:15:55 +0300 Subject: [PATCH] Added extension to field to use numbers as first class citizens --- .../src/main/kotlin/scientifik/kmath/operations/Algebra.kt | 7 +++++-- .../kmath/expressions/FieldExpressionContextTest.kt | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/kmath-common/src/main/kotlin/scientifik/kmath/operations/Algebra.kt b/kmath-common/src/main/kotlin/scientifik/kmath/operations/Algebra.kt index 985cf3b14..4613dda7c 100644 --- a/kmath-common/src/main/kotlin/scientifik/kmath/operations/Algebra.kt +++ b/kmath-common/src/main/kotlin/scientifik/kmath/operations/Algebra.kt @@ -6,7 +6,7 @@ package scientifik.kmath.operations * @param T the self type of the element * @param S the type of mathematical context for this element */ -interface MathElement{ +interface MathElement { /** * The context this element belongs to */ @@ -53,7 +53,7 @@ interface Space { * @param T self type of the element. Needed for static type checking * @param S the type of space */ -interface SpaceElement>: MathElement { +interface SpaceElement> : MathElement { /** * Self value. Needed for static type checking. Needed to avoid type erasure on JVM. @@ -101,6 +101,9 @@ interface Field : Ring { operator fun T.div(b: T): T = divide(this, b) operator fun Number.div(b: T) = this * divide(one, b) + + operator fun T.plus(b: Number) = this.plus(b * one) + operator fun Number.plus(b: T) = b + this } /** diff --git a/kmath-common/src/test/kotlin/scientifik/kmath/expressions/FieldExpressionContextTest.kt b/kmath-common/src/test/kotlin/scientifik/kmath/expressions/FieldExpressionContextTest.kt index 5e9832604..3d68a4674 100644 --- a/kmath-common/src/test/kotlin/scientifik/kmath/expressions/FieldExpressionContextTest.kt +++ b/kmath-common/src/test/kotlin/scientifik/kmath/expressions/FieldExpressionContextTest.kt @@ -10,7 +10,7 @@ class FieldExpressionContextTest { val context = FieldExpressionContext(DoubleField) val expression = with(context) { val x = variable("x", 2.0) - x * x + 2 * x + 1.0 * one + x * x + 2 * x + 1.0 } assertEquals(expression("x" to 1.0), 4.0) assertEquals(expression(), 9.0)