JetBrains-Research / viktor

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

More idiomatic and efficient computations #25

Open dievsky opened 5 years ago

dievsky commented 5 years ago

Currently it's hard to chain computations efficiently. If you write a.exp() * 2.0 - 1.0, it creates two unnecessary copies. To avoid this, you have to do it either with three lines:

val b = a.exp()
b *= 2.0
b -= 1.0

or with an unreadable mess of apply-s:

val b = a.copy().apply { expInPlace() }.apply { timesAssign(2.0) }.apply { minusAssign(1.0) }

It would be much easier if in-place and assign methods allowed chaining.

This is sadly impossible for the assign operators, since they are required by language to only return Unit, but we can provide equivalent methods with differing names to circumvent this, e.g.

val b = a.exp().timesInPlace(2.0).minusInPlace(1.0)

Another, more difficult but equally more intriguing possibility, is to somehow enable delayed computations, so that the user would describe what needs to be computed and how to compute it, and the library would then choose between in-place and copying methods to satisfy these requirements. I don't currently have a clear idea of how to implement this.