3

I need to iterate part of an array backwards. I'd like to do that "functionally" as it's more comprehensible, like that

for (b in buf.sliceArray(0 until bufLimit).reversedArray()) {}

But both sliceArray and reversedArray are not lazy. Is there a lazy version or should I probably fall back to

for (bIdx in bufLimit - 1 downTo 0) {
    val b = buf[bIdx]
}

which is more confusing and verbose?

2
  • What about this? buf.take(bufLimit).reversed().forEach { ... } Commented Feb 23, 2017 at 20:11
  • @marstran ByteArray.take as well isn't lazy, it creates an ArrayList Commented Feb 23, 2017 at 20:16

2 Answers 2

2

If you use a list instead of an array, then you can reverse it and then convert to a Sequence:

val buf: List = listOf(1, 2, 3, 4, 5)
val bufLimit = 3

for (b in buf.asReversed().asSequence().drop(buf.size - bufLimit)) {
    println(b)
}

Functions with the as prefix only wrap objects without copying, so the code above does not copy the buf content.

Note that you shouldn't loose any performance compared to Array if you use an ArrayList.

However this solution does involve several iterators, so it is somewhat less efficient than the index code you have suggested in the question:

for (bIdx in bufLimit - 1 downTo 0) {
    val b = buf[bIdx]
} 
Sign up to request clarification or add additional context in comments.

Comments

1

I suggest creating an extension function to handle your specific use case. e.g.:

/**
 * Performs the given [action] on each element at the specified [indices].
 */
inline fun ByteArray.forEachAt(indices: Iterable<Int>, action: (Byte) -> Unit): Unit {
    indices.forEach { index -> action(this[index]) }
}

Usage:

buf.forEachAt((0 until bufLimit).reversed)) {}
// or
buf.forEachAt(bufLimit - 1 downTo 0) {}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.