Functions to manipulate ranges

Currently there are no methods to transform or combine ranges. Either you need to manually create a new range instance by coping all parameters, including the step of the IntProgression, even if the step didn’t change, either you need to unfold a range into an Iterable and use methods from there, but it’s not resource-efficient.

E.g.:
(1..5).shift(1)
result: 2..6
(1..5).intersect(3..8)
result: 3..5

4 Likes

Kotlin ranges are fairly limited. Once you go down this path of adding seemingly trivial operations, you run into added complexity. E.g., adding/subtracting ranges will need a representation of unions of ranges. And, integers need to be treated differently from floating point types. You’ll start running into overflows and need to think about how to deal with that. And you may end up needing both lower and upper inclusive/exclusive bounds.

Having written a similar library in C# before which proved super useful in everyday tasks, I have started writing a similar library for kotlin doing the same: Whathecode/kotlinx.interval: Kotlin multiplatform bounded open/closed generic intervals. (github.com)

This can be a useful reference to see the design considerations which may become relevant when tackling this. For now, I simply look at “intervals” as a separate thing than Kotlin ranges. Likely, it is a subset.

1 Like