Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through odd members of collection in Scala

What is an efficient way to iterate through only the odd members of a collection in Scala, based on index position?

Given this list:

val fruits: List[String] = List("apples", "oranges", "pears", "bananas")

I want to to skip apples and pears, and process oranges and bananas. Thanks!

Update based on responses given:

Wow, each of the top three answers has merit. I originally meant the word "efficient" from a Scala Collections syntax perspective, and I was really just looking for a slick way to create the sublist for subsequent iteration. @Senia does a good job introducing the sliding() function, great for this particular use case, but I also like @Brian's more generalized approach using zipWithIndex().

However, when I consider the actual wording of the question as originally asked and the computational efficiency of @sourcedelica's response, I think he takes the prize for this one.

like image 398
kgx Avatar asked Oct 08 '12 04:10

kgx


2 Answers

scala> List("apples", "oranges", "pears", "bananas").drop(1).sliding(1, 2).flatten.toList
res0: List[java.lang.String] = List(oranges, bananas)
like image 81
senia Avatar answered Sep 26 '22 09:09

senia


val fruits: List[String] = List("apples", "oranges", "pears", "bananas")

fruits.zipWithIndex.filter(_._2 % 2 == 1).map(_._1)

res0: List[String] = List(oranges, bananas)

zipWithIndex pairs each element in List with an index giving:

List[(String, Int)] = List((apples,0), (oranges,1), (pears,2), (bananas,3))

filter the odd elements with filter(_._2 % 2 == 1) giving:

List[(String, Int)] = List((oranges,1), (bananas,3))

map the List[(String, Int)] to just List[String] by taking the first element of each tuple with .map(_._1) giving:

List[String] = List(oranges, bananas)

like image 22
Brian Avatar answered Sep 26 '22 09:09

Brian