Skip to content

Instantly share code, notes, and snippets.

@kageru
Created July 2, 2019 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kageru/01669c5f6fc9a40be8a5d791add4549f to your computer and use it in GitHub Desktop.
Save kageru/01669c5f6fc9a40be8a5d791add4549f to your computer and use it in GitHub Desktop.
Mainly a proof of concept. There are better ways to do this, but it was a quick experiment to create something like Python’s slicing in Kotlin.
import kotlin.math.min
object start {
infix fun to(other: Int) = RangeTuple(0, other)
infix fun to(other: end) = RangeTuple(0, Int.MAX_VALUE)
}
object end
infix fun Int.to(other: end) = RangeTuple(this, Int.MAX_VALUE)
class RangeTuple(val first: Int, val last: Int)
fun <T> effectiveIndex(index: Int, list: List<T>): Int {
return min(list.size, if (index < 0) list.size + index else index)
}
operator fun <T> List<T>.get(range: RangeTuple): List<T> {
return this.subList(effectiveIndex(range.first, this), effectiveIndex(range.last, this))
}
infix fun Int.to(other: Int): RangeTuple {
return RangeTuple(this, other)
}
fun main() {
val list = listOf(1, 2, 3, 4)
println(list[1 to 3]) // [2, 3]
println(list[0 to -1]) // [1, 2, 3]
println(list[-2 to -1]) // [3]
println(list[start to end]) // [1, 2, 3, 4]
println(list[start to 3]) // [1, 2, 3]
println(list[-2 to end]) // [3, 4]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment