JetBrains-Research / viktor

Efficient f64-only ndarray in Kotlin
MIT License
125 stars 6 forks source link

Provide reduce method #41

Closed dievsky closed 3 years ago

dievsky commented 3 years ago

It would be nice to have a general reduction method.

Jolanrensen commented 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
}
dievsky commented 3 years ago

Exactly like this, but with an initial value and specialized for dense arrays.

Jolanrensen commented 3 years ago

With initial value? That's not reduce, that's fold, right?

dievsky commented 3 years ago

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.

Jolanrensen commented 3 years ago

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

dievsky commented 3 years ago

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?

Jolanrensen commented 3 years ago

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.