Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard Kotlin function for splitting a Sequence into a head and a tail?

Tags:

kotlin

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.

like image 616
Duncan McGregor Avatar asked Dec 21 '20 17:12

Duncan McGregor


People also ask

What is asSequence Kotlin?

asSequence(): Sequence<T> Creates a Sequence instance that wraps the original collection returning its elements when being iterated.

What is chunked in Kotlin?

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.

What is the key difference between iterable T and sequence T in Kotlin?

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.

What is the default return type of any functions defined in Kotlin?

I know unit is the default return type in kotlin.


1 Answers

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
    }
}
like image 86
Ben P. Avatar answered Sep 19 '22 08:09

Ben P.