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.
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.
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
}
}