|
| 1 | +# Open-ended ranges and rangeUntil operator |
| 2 | + |
| 3 | +* **Type**: Design proposal / Standard Library API proposal |
| 4 | +* **Author**: Ilya Gorbunov |
| 5 | +* **Contributors**: Roman Elizarov, Vsevolod Tolstopyatov, Abduqodiri Qurbonzoda, Leonid Startsev, Egor Tolstoy |
| 6 | +* **Status**: Experimental |
| 7 | +* **Prototype**: Implemented in 1.7.20-Beta |
| 8 | +* **Related issues**: [KT-15613](https://youtrack.jetbrains.com/issue/KT-15613) |
| 9 | +* **Discussion**: [KEEP-314](https://github.com/Kotlin/KEEP/issues/314) |
| 10 | + |
| 11 | +## Summary |
| 12 | + |
| 13 | +Kotlin since its beginning has the `..` operator to express a range of values. |
| 14 | +Similar to natural languages, the expression `a..b` means the range that includes both of its bounds. |
| 15 | + |
| 16 | +However, in programming it's often the case that a typical data structure has its indices starting at 0 |
| 17 | +and ending one before the number of elements in it, so to iterate these indices, the range `0..(size - 1)` has to be used. |
| 18 | +For such a common use case, Kotlin standard library provides various shortcut functions, such as |
| 19 | +the `indices` extension property available on many data structures returning that `0..(size - 1)` range, |
| 20 | +the `lastIndex` extension property returning the last index value, namely `size - 1`, and finally the `until` infix function |
| 21 | +allowing to instantiate a range of discrete integral values like `0 until size` which is equivalent to `0..(size - 1)`. |
| 22 | + |
| 23 | +Despite all of this, due to asymmetry between `..` and `until`, the former is used more often, even in cases where the latter would be more clear. |
| 24 | +Also, our UX research shows that Kotlin newcomers have troubles remembering whether the upper bound of the range produced by `until` |
| 25 | +is exclusive or inclusive. |
| 26 | + |
| 27 | +To mitigate that, we propose to introduce the operator `..<` in Kotlin that would be |
| 28 | +on par with the `..` operator and make it very clear that the upper bound is not included. |
| 29 | + |
| 30 | +## Use cases |
| 31 | + |
| 32 | +Currently, the use cases of the new operator are mostly covered by the `until` function, that corrects the upper bound |
| 33 | +returning a closed range of integral values that would be equivalent to an open-ended range. |
| 34 | +However, the `until` function is available only for integral or discrete argument types, such as `Int`, `Long`, `Char`, |
| 35 | +and having the new operator gives a chance for introducing open-ended ranges for those type that didn't have it before. |
| 36 | + |
| 37 | +### Iterating indices of a data structure |
| 38 | + |
| 39 | +Typically, data structures start indexing at zero and thus most indexed loops on these data structures |
| 40 | +have the form of `for (index in 0 until size)`. Such a common use case deserves introducing a designated operator with |
| 41 | +a clear meaning. |
| 42 | + |
| 43 | +### Discretization and bucketing of continuous values |
| 44 | + |
| 45 | +Discretization and binning require splitting the domain of a continuous value to a number of non-overlapping intervals. |
| 46 | +Such intervals are usually chosen as ranges that include their lower bound and exclude the upper bound, so that two |
| 47 | +adjacent ranges neither have a point where they overlap, nor a point between them that is not contained in these ranges. |
| 48 | + |
| 49 | +Even sometimes when the value is already discrete, for example, when it is expressed as a `Double` number, |
| 50 | +and it is possible to represent a half-open range with a closed one by adjusting one of its bounds, |
| 51 | +in practice it is not convenient to work with such ranges: |
| 52 | + |
| 53 | +```kotlin |
| 54 | +val equivalent = 1.0..2.0.nextDown() // contains the same values as 1.0..<2.0 range |
| 55 | +println(eqivalent) // 1..1.9999999999999998 |
| 56 | +``` |
| 57 | + |
| 58 | +## Similar API review |
| 59 | + |
| 60 | +### Languages that distinguish end-inclusive and end-exclusive ranges |
| 61 | + |
| 62 | +- Swift: `...` end-inclusive range, `..<` end-exclusive, supports one-sided ranges |
| 63 | +- Ruby: `..` end-inclusive range, `...` end-exclusive, supports one-sided ranges |
| 64 | +- Groovy: `..` end-inclusive range, `..<` end-exclusive, `<..` start-exclusive, `<..<` both bounds-exclusive range |
| 65 | + |
| 66 | + |
| 67 | +### Libraries for representing ranges |
| 68 | + |
| 69 | +- Guava library provides the single `Range` class capable of representing full variety of mathematical range types: |
| 70 | + closed, open, unbounded. The range is defined by the properties `hasLower/UpperBound` which indicate whether the range is bounded or not, |
| 71 | + and then with `lower/upperEndPoint` and `lower/upperBoundType` properties which can be obtained only if the range has that bound. |
| 72 | + See https://github.com/google/guava/wiki/RangesExplained for details. |
| 73 | + |
| 74 | +- Groovy supports [_number_ ranges](https://docs.groovy-lang.org/latest/html/api/groovy/lang/NumberRange.html) (including `IntRange`) |
| 75 | + with bounds being individually excluded or included. This is indicated by `inclusiveLeft` and `inclusiveRight` properties. |
| 76 | + However, the base [Range](https://docs.groovy-lang.org/latest/html/api/groovy/lang/Range.html) interface doesn't indicate inclusiveness and |
| 77 | + has somewhat contradictory contract of `containsWithinBounds` function. |
| 78 | + |
| 79 | +- Swift distinguishes open-ended [`Range`](https://developer.apple.com/documentation/swift/range) and closed [`ClosedRange`](https://developer.apple.com/documentation/swift/closedrange) |
| 80 | + structures. |
| 81 | + |
| 82 | +- [kotlin-statistics](https://github.com/thomasnield/kotlin-statistics/blob/master/src/main/kotlin/org/nield/kotlinstatistics/range) |
| 83 | + library provides the base `Range` type and individual types for each combination of included/excluded bounds: |
| 84 | + `OpenRange`, `OpenClosedRange`, `ClosedOpenRange`, `XClosedRange`. |
| 85 | + |
| 86 | +- [kotlinx-interval](https://github.com/Whathecode/kotlinx.interval) library uses approach similar to Groovy, but in a more generic fashion: |
| 87 | + the base `Interval` type indicates whether bounds are inclusive or exclusive with the boolean properties |
| 88 | + `isStartIncluded`/`isEndIncluded` |
| 89 | + |
| 90 | + |
| 91 | +## Language changes |
| 92 | + |
| 93 | +In order to use the new `..<` operator in code and be able to overload it for user types, |
| 94 | +we provide the following operator convention: |
| 95 | + |
| 96 | +```kotlin |
| 97 | +operator fun FromType.rangeUntil(to: ToType): RangeType |
| 98 | +``` |
| 99 | + |
| 100 | +Similar to `rangeTo` operator, this operator convention can be satisfied either with a member |
| 101 | +or an extension function taking `FromType`, the type of the first operand, as the receiver, and `ToType`, the type of the second operand, as the parameter. |
| 102 | +Usually `FromType` and `ToType` refer to the same type. |
| 103 | + |
| 104 | +## API Details |
| 105 | + |
| 106 | +When introducing `rangeUntil` operator support in the standard library, we pursue the following goals: |
| 107 | + |
| 108 | +- for consistency, `rangeUntil` operator should be provided for the same types that currently have `rangeTo` operator; |
| 109 | +- `rangeUntil` should return an instance of type representing open-ended ranges; |
| 110 | +- it should be an easy and compatible change to replace the existing `until` function with the `..<` operator. |
| 111 | + Therefore, the type returned by `rangeUntil` should be the same type or a subtype of the type that is currently |
| 112 | + returned by `until` for the given argument types. |
| 113 | + |
| 114 | +The following new types and operations will be introduced in the `kotlin.ranges` packages in the common Kotlin standard library. |
| 115 | + |
| 116 | +### OpenEndRange interface |
| 117 | + |
| 118 | +The new interface to represent open-ended ranges is very similar to the existing `ClosedRange<T>` interface: |
| 119 | + |
| 120 | +```kotlin |
| 121 | +interface OpenEndRange<T : Comparable<T>> { |
| 122 | + // lower bound |
| 123 | + val start: T |
| 124 | + // upper bound, not included in the range |
| 125 | + val endExclusive: T |
| 126 | + |
| 127 | + operator fun contains(value: T): Boolean = value >= start && value < endExclusive |
| 128 | + |
| 129 | + fun isEmpty(): Boolean = start >= endExclusive |
| 130 | +} |
| 131 | +``` |
| 132 | + |
| 133 | +The difference is that it has the property `endExclusive` for the upper bound instead of `endInclusive` and uses different comparison |
| 134 | +operators when comparing with the upper bound. |
| 135 | + |
| 136 | +### Implementing OpenEndRange in the existing iterable ranges |
| 137 | + |
| 138 | +Currently, in a situation when a user needs to get a range with excluded upper bound, they use `until` function producing |
| 139 | +a closed iterable range effectively with the same values. In order to make these ranges acceptable in the new API that takes |
| 140 | +`OpenEndRange<T>`, we want to implement that interface in the existing iterable ranges: `IntRange`, `LongRange`, `CharRange`, |
| 141 | +`UIntRange`, `ULongRange`. So they will be implementing both `ClosedRange<T>` and `OpenEndRange<T>` interfaces simultaneously. |
| 142 | + |
| 143 | +```kotlin |
| 144 | +class IntRange : IntProgression(...), ClosedRange<Int>, OpenEndRange<Int> { |
| 145 | + override val start: Int |
| 146 | + override val endInclusive: Int |
| 147 | + override val endExclusive: Int |
| 148 | +} |
| 149 | +``` |
| 150 | + |
| 151 | +There's a subtlety in implementing `endExclusive` property in such ranges: usually it returns `endInclusive + 1`, but |
| 152 | +there can be such ranges where `endInclusive` is already the maximum value of the range type, and so adding one to it |
| 153 | +would overflow. |
| 154 | + |
| 155 | +We decided that in such cases the reasonable behavior would be to throw an exception from the `endExclusive` property |
| 156 | +getter. The possibility of that will be documented in the base interface, `OpenEndRange`, and additionally the implementation |
| 157 | +of that property will be deprecated in the existing concrete range classes. |
| 158 | + |
| 159 | +### rangeUntil operators for the standard types |
| 160 | + |
| 161 | +`rangeUntil` operators will be provided for the same types and their combinations that currently have `rangeTo` operator defined. |
| 162 | +For the purposes of prototype, we provide them as extension functions, but for consistency we plan to make them members |
| 163 | +later, before stabilizing the open-ended ranges API. |
| 164 | + |
| 165 | +### Generic open-ended ranges of comparable values |
| 166 | + |
| 167 | +Similar to closed ranges, there will be a function instantiating an open-ended range from any two values of a comparable type: |
| 168 | + |
| 169 | +```kotlin |
| 170 | +operator fun <T : Comparable<T>> T.rangeUntil(that: T): OpenEndRange<T> |
| 171 | +``` |
| 172 | + |
| 173 | +### Specialized open-ended ranges of floating point numbers |
| 174 | + |
| 175 | +There also will be two static specializations of `rangeUntil` operator for `Double` and `Float` types of arguments. |
| 176 | +They are special in how they compare values of their bounds with the value passed to `contains` and between themselves, |
| 177 | +so that a range where either bound is NaN is empty, and the `NaN` value is not contained in any range. |
| 178 | + |
| 179 | +```kotlin |
| 180 | +operator fun Double.rangeUntil(that: Double): OpenEndRange<Double> |
| 181 | +operator fun Float.rangeUntil(that: Float): OpenEndRange<Float> |
| 182 | +``` |
| 183 | + |
| 184 | +## Experimental status |
| 185 | + |
| 186 | +Both the language feature of `rangeUntil` operator and its supporting standard library API |
| 187 | +are to be released in Kotlin 1.7.20 in [Experimental](https://kotlinlang.org/docs/components-stability.html#stability-levels-explained) status. |
| 188 | + |
| 189 | +In order to use `..<` operator or to implement that operator convention for own types, |
| 190 | +the corresponding language feature should be enabled with the `-XXLanguage:+RangeUntilOperator` compiler argument. |
| 191 | + |
| 192 | +The new API elements introduced to support the open-ended ranges of the standard types |
| 193 | +require an opt-in as usual experimental stdlib API: |
| 194 | +`@OptIn(ExperimentalStdlibApi::class)`. Alternatively, a compiler argument `-opt-in=kotlin.ExperimentalStdlibApi` |
| 195 | +can be specified. |
| 196 | + |
| 197 | +We recommend library developers to [propagate](https://kotlinlang.org/docs/opt-in-requirements.html#propagating-opt-in) the opt-in requirement, |
| 198 | +if they use experimental API in their code. |
| 199 | + |
| 200 | +## Alternatives |
| 201 | + |
| 202 | +### Adapt the existing range interface for open-ended ranges |
| 203 | + |
| 204 | +Instead of introducing a new interface for open-ended ranges, reuse the existing range interface and |
| 205 | +add a boolean parameter indicating whether the bound is included or excluded. |
| 206 | + |
| 207 | +- pro: such approach is similar to one used in Groovy and Guava and allows to support ranges with an open lower bound later |
| 208 | +without introducing a new type |
| 209 | +- con: the existing users of `ClosedRange` type would be very unprepared and surprised if the range begins to exclude its bound |
| 210 | + indicating that with a new boolean property. |
| 211 | +- con: it would be impossible to represent both closed and equivalent open-ended integral range with the same instance, |
| 212 | + so changing `until` to `..<` would be a more painful change. |
| 213 | + |
| 214 | + |
| 215 | +## Open questions and considerations |
| 216 | + |
| 217 | +### Search friendliness |
| 218 | + |
| 219 | +Usually internet search engines disregard punctuation characters, so it might be |
| 220 | +hard to find what `..<` means in Kotlin. For example, currently the search https://www.google.com/search?q=swift+operator+..%3C |
| 221 | +doesn't show any relevant results about that Swift range operator. |
| 222 | + |
| 223 | +### Common supertype of ClosedRange and OpenEndRange |
| 224 | + |
| 225 | +If the range of a value is closed, for example `0.0..1.0`, then splitting it into a number of ranges |
| 226 | +will require a combination of open-ended ranges and one closed range in the end, e.g.: |
| 227 | +`0.0..<0.1`, `0.1..<0.2`, ..., `0.9..1.0`. |
| 228 | +Putting these ranges into a list would make its element type inferred to `Any`, and that would make working with elements inconvenient. |
| 229 | + |
| 230 | +Introducing a more dedicated common supertype of the `ClosedRange` and `OpenEndRange` could help in this situation, |
| 231 | +however, it's unclear what useful operations such supertype would provide. |
0 commit comments