Scala filter on a list by index

前端 未结 6 1371
一整个雨季
一整个雨季 2021-02-15 12:52

I wanted to write it functionally, and the best I could do was:

list.zipWithIndex.filter((tt:Tuple2[Thing,Int])=>(tt._2%3==0)).unzip._1

to g

6条回答
  •  渐次进展
    2021-02-15 13:21

    If efficiency is not an issue, you could do the following:

    list.grouped(3).map(_.head)
    

    Note that this constructs intermediate lists.

    Alternatively you can use a for-comprehension:

    for {
      (x,i) <- list zipWithIndex
      if i % 3 == 0
    } yield x
    

    This is of course almost identical to your original solution, just written differently.

    My last alternative for you is the use of collect on the zipped list:

    list.zipWithIndex.collect {
      case (x,i) if i % 3 == 0 => x
    }
    

提交回复
热议问题