diff --git a/kmath-core/src/commonMain/kotlin/scientifik/kmath/operations/AlgebraExtensions.kt b/kmath-core/src/commonMain/kotlin/scientifik/kmath/operations/AlgebraExtensions.kt index 6712d3baa..00b16dc98 100644 --- a/kmath-core/src/commonMain/kotlin/scientifik/kmath/operations/AlgebraExtensions.kt +++ b/kmath-core/src/commonMain/kotlin/scientifik/kmath/operations/AlgebraExtensions.kt @@ -4,7 +4,7 @@ package scientifik.kmath.operations * Returns the sum of all elements in the iterable in this [Space]. * * @receiver the algebra that provides addition. - * @param data the collection to sum up. + * @param data the iterable to sum up. * @return the sum. */ fun Space.sum(data: Iterable): T = data.fold(zero) { left, right -> add(left, right) } @@ -13,11 +13,29 @@ fun Space.sum(data: Iterable): T = data.fold(zero) { left, right -> ad * Returns the sum of all elements in the sequence in this [Space]. * * @receiver the algebra that provides addition. - * @param data the collection to sum up. + * @param data the sequence to sum up. * @return the sum. */ fun Space.sum(data: Sequence): T = data.fold(zero) { left, right -> add(left, right) } +/** + * Returns an average value of elements in the iterable in this [Space]. + * + * @receiver the algebra that provides addition and division. + * @param data the iterable to find average. + * @return the average value. + */ +fun Space.average(data: Iterable): T = sum(data) / data.count() + +/** + * Returns an average value of elements in the sequence in this [Space]. + * + * @receiver the algebra that provides addition and division. + * @param data the sequence to find average. + * @return the average value. + */ +fun Space.average(data: Sequence): T = sum(data) / data.count() + /** * Returns the sum of all elements in the iterable in provided space. * @@ -25,7 +43,34 @@ fun Space.sum(data: Sequence): T = data.fold(zero) { left, right -> ad * @param space the algebra that provides addition. * @return the sum. */ -fun > Iterable.sumWith(space: S): T = space.sum(this) +fun Iterable.sumWith(space: Space): T = space.sum(this) + +/** + * Returns the sum of all elements in the sequence in provided space. + * + * @receiver the collection to sum up. + * @param space the algebra that provides addition. + * @return the sum. + */ +fun Sequence.sumWith(space: Space): T = space.sum(this) + +/** + * Returns an average value of elements in the iterable in this [Space]. + * + * @receiver the iterable to find average. + * @param space the algebra that provides addition and division. + * @return the average value. + */ +fun Iterable.averageWith(space: Space): T = space.average(this) + +/** + * Returns an average value of elements in the sequence in this [Space]. + * + * @receiver the sequence to find average. + * @param space the algebra that provides addition and division. + * @return the average value. + */ +fun Sequence.averageWith(space: Space): T = space.average(this) //TODO optimized power operation