I'm thinking of something with a signature like fun <T> Sequence<T>.destruct(): Pair<T, Sequence<T>>?
which would return null
for an empty sequence, otherwise a pair of the first and rest of the receiver.
asSequence(): Sequence<T> Creates a Sequence instance that wraps the original collection returning its elements when being iterated.
Splits this collection into a list of lists each not exceeding the given size. The last list in the resulting list may have fewer elements than the given size.
The order of operations execution is different as well: Sequence performs all the processing steps one-by-one for every single element. In turn, Iterable completes each step for the whole collection and then proceeds to the next step.
I know unit is the default return type in kotlin.
I believe the answer is "no." This page lists all of the standard Sequence
functions, and a search for "pair" doesn't turn up anything that seems to match what you want.
That said, there is a standard firstOrNull()
function as well as a drop()
function, so you could write your own pretty easily:
fun <T> Sequence<T>.destruct() =
firstOrNull()?.let { it to drop(1) }
If you are working with sequences that can only be consumed once, the above won't work (as both firstOrNull()
and (eventually) DropSequence
will invoke the receiver's iterator()
method). You could work around this by following the same general idea but being more explicit about how iterator()
is called:
fun <T> Sequence<T>.destruct(): Pair<T, Sequence<T>>? {
val iterator = iterator()
return if (iterator.hasNext()) {
iterator.next() to iterator.asSequence()
} else {
null
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With