is there a simple way to window a `Sequence` based...
# stdlib
m
is there a simple way to window a
Sequence
based on attributes of the data? for example, if i have
Copy code
sequenceOf(1,2,3,5,6,8,10,14,15)
i'd like to "merge" contiguous elements together into a sequence that is
Copy code
sequenceOf([1,2,3], [5,6], [8], [10], [14,15])
i'd like to retain the lazy evaluation, such that
[1,2,3]
is yielded only when it is needed
s
I don’t think there’s a simple way
m
hah, kind of figured.
s
you could build a sequence that’s smart enough to read just enough of the data source to determine where to set the window boundaries, but afaik there isn’t like a simple pass-in-a-lambda solution in the stdlib
l
Can't
fold
do this?
e
Coroutines to the rescue:
Copy code
fun Sequence<Int>.contiguous() = sequence<List<Int>> {
    val cur = mutableListOf<Int>()
    for (x in this@contiguous) {
        if (cur.isNotEmpty() && x != cur.last() + 1) {
            yield(cur.toList())
            cur.clear()
        }
        cur += x
    }
    if (cur.isNotEmpty()) yield(cur)
}
m
@Shawn good suggestion, that is essentially what i ended up doing @louiscad i think
fold
would be terminal and consume all of the elements (unless i'm missing something) @elizarov that's close to how i did it, except i used
Sequence.iterator
with
hasNext
as my looping condition i think your approach is cleaner, and im going to change mine to more closely follow your model thanks for the help everybody!