https://kotlinlang.org logo
#stdlib
Title
# stdlib
m

mkobit

04/19/2019, 6:27 PM
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

Shawn

04/19/2019, 6:45 PM
I don’t think there’s a simple way
m

mkobit

04/19/2019, 6:46 PM
hah, kind of figured.
s

Shawn

04/19/2019, 6:46 PM
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

louiscad

04/19/2019, 7:20 PM
Can't
fold
do this?
e

elizarov

04/21/2019, 1:26 PM
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

mkobit

04/22/2019, 1:39 PM
@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!
4 Views