Implement reduce and reduceRight functions

This commit is contained in:
Alexander Zolotov
2012-06-16 00:46:20 +04:00
parent 4657567484
commit 0043454a06
14 changed files with 398 additions and 3 deletions
@@ -147,6 +147,36 @@ public inline fun DoubleArray.fold(initial: Double, operation: (Double, Double)
*/
public inline fun DoubleArray.foldRight(initial: Double, operation: (Double, Double) -> Double): Double = reverse().fold(initial, {x, y -> operation(y, x)})
/**
* Applies binary operation to all elements of iterable, going from left to right.
* Similar to fold function, but uses the first element as initial value
*
* @includeFunctionBody ../../test/CollectionTest.kt reduce
*/
public inline fun DoubleArray.reduce(operation: (Double, Double) -> Double): Double {
val iterator = this.iterator().sure()
if (!iterator.hasNext) {
throw UnsupportedOperationException("Empty iterable can't be reduced")
}
var result: Double = iterator.next() //compiler doesn't understand that result will initialized anyway
while (iterator.hasNext) {
result = operation(result, iterator.next())
}
return result
}
/**
* Applies binary operation to all elements of iterable, going from right to left.
* Similar to foldRight function, but uses the last element as initial value
*
* @includeFunctionBody ../../test/CollectionTest.kt reduceRight
*/
public inline fun DoubleArray.reduceRight(operation: (Double, Double) -> Double): Double = reverse().reduce { x, y -> operation(y, x) }
/**
* Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by
*