Search code examples
kotlinsequencespurely-functional

Unweave sequence, Kotlin functional/streaming idiom


I have a sequence of interleaved data (with fixed stride) and I'd like to reduce it to a single value for each "structure" (n*stride values to n values).

I could just use loop writing into the mutable list with selected step for reader index, but I'm looking for more functional and readable approach. Any thoughts?

For example: Input sequence consists of RGB triplets (stride 3) and output is grayscale.

Imperative way is like:

fun greyscale(stream:List<Byte>):List<Byte>{
    val out = ArrayList(stream.size / 3)
    var i = 0; var o = 0
    while(i < stream.size)
        out[o++]=(stream[i++] + stream[i++] + stream[i++])/3
    return out
}

How can I make something like that without explicitly implementing a function and mutable container, but purely on functional extensions like .map and so on?


Solution

  • Kotlin 1.2 (Milestone 1 was released yesterday) brings the chunked method on collections. It chunks up the collection into blocks of a given size. You can use this to implement your function:

    fun greyscale(stream: List<Byte>): List<Byte> = 
          stream.chunked(3)
                .map { (it.sum() / 3).toByte() }