Closed dievsky closed 3 years ago
So, something like this?
inline fun F64FlatArray.reduce(operation: (acc: Double, Double) -> Double): Double {
if (size == 0) throw UnsupportedOperationException("Empty array can't be reduced.")
var accumulator = this[0]
var i = 1
while (i < size) {
accumulator = operation(accumulator, this[i++])
}
return accumulator
}
Exactly like this, but with an initial value and specialized for dense arrays.
With initial value? That's not reduce, that's fold, right?
Yep, my terminology was incorrect. Now that I've got it in check, I can say I prefer fold
to reduce
, since it's a bit cleaner.
Reduce is also very useful though. It's just that the initial value then is the first item in the collection. So having them both would be best probably :)
Frankly, I seem hard-pressed to think of a use-case where reduce
can't be readily expressed as fold
. Can you give me an example?
You can but it might not make much sense to do it. For instance reducing by sum. You could do it with a fold that starts at 0, but you'd have to add the 0 somewhere whereas with a reduce it wouldn't. Same with a reduce by product, having to start off with a 1. Simply having a reduce and fold (like in the kotlin standard library) I think is the best option.
It would be nice to have a general reduction method.