Thread
#stdlib
    m

    mkobit

    3 years ago
    is there a simple way to window a
    Sequence
    based on attributes of the data? for example, if i have
    sequenceOf(1,2,3,5,6,8,10,14,15)
    i'd like to "merge" contiguous elements together into a sequence that is
    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
    Shawn

    Shawn

    3 years ago
    I don’t think there’s a simple way
    m

    mkobit

    3 years ago
    hah, kind of figured.
    Shawn

    Shawn

    3 years ago
    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
    louiscad

    louiscad

    3 years ago
    Can't
    fold
    do this?
    elizarov

    elizarov

    3 years ago
    Coroutines to the rescue:
    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

    3 years ago
    @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!