Hi just wondering is there an idiomatic iteration ...
# getting-started
l
Hi just wondering is there an idiomatic iteration pairwise over a list or array, eg:
a b c d
iterated as
a b; b c; c d
. This is to calculate the delta between elements
d
Copy code
val list = listOf(1, 2, 3, 4, 5, 6)
println(list.zipWithNext())
Prints:
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
l
thank you!!! ✌️✌️✌️
Out of curiosity is there a way to keep mapping functions returning arrays instead of lists? (I'm Assuming there is better performance with arrays because the items should be linearly in memory)
p
if you want to transform pairwise,
zipWithNext
also takes a transformation. i.e.
Copy code
list.zipWithNext { a, b -> a - b }
l
That is beautiful
p
if you just want to iterate and process, without mapping to a collection, you can use a sequence
d
Lists use arrays under the hood, there should not be a significant performance difference.
p
however you can avoid the intermediate lists when using multiple steps (or just iterating over the result) by using sequences, which may have an impact on performance.
l
Nice, so it sounds like Sequence is a generic forward iterator like
iter()
in python
k
But then the lambdas aren't inlined so it's a tradeoff unfortunately. And either way everything is going to be boxed, so performance won't be great.
l
Yeah I was kind of looking around for a
numpy
type thing for kotlin...
m
https://youtrack.jetbrains.com/issue/KT-21997 implementing this would eliminate the issue
although it doesn't look like a simple problem to solve