Was trying to look it up, but didn't find anything...
# stdlib
s
Was trying to look it up, but didn't find anything related: What about adding std lib function to cut List into two sublists before/after certain index? I know this could be easily implemented but found this to be not so rare use case after all. Take something like this for example:
Copy code
fun <T> List<T>.cut(cutIndex: Int): Pair<List<T>, List<T>> {
    if (cutIndex !in indices) throw IndexOutOfBoundsException("cutIndex $cutIndex out of bounds for List indices $indices")
    return subList(0, cutIndex) to subList(cutIndex, size)
}

fun <T> List<T>.cutInHalf(): Pair<List<T>, List<T>> {
    val midIndex = size / 2
    return subList(0, midIndex) to subList(midIndex, size)
}
Having
val sampleList = listOf(1, 8, 3, 9, 12, 4)
sampleList.cutInHalf()
would result in
([1, 8, 3], [9, 12, 4])
sampleList.cut(4)
would result in
([1, 8, 3, 9], [12, 4])
etc.
cutInHalf
wouldn't be ideal for Lists with odd number of elements, but I guess that should be obvious
e
I think your check is too strict;
emptyList<Any>().cut(0)
will throw, but shouldn't
this function is named splitAt in Haskell, which is a better name IMO
👍 1
alas it should probably be copying by default to match the behavior of most other stdlib functions (e.g. using
.slice()
instead of
.subLst()
) but maybe you do want a view sometimes
k
fun <T> List<T>.splitAt(index: Int) = take(index) to drop(index)
is such a short definition that it's probably just as readable to use
take(index) to drop(index)
every time instead of defining a separate function. (This creates new Lists, which you may or may not want.)