Scala filter on a list by index

前端 未结 6 1351
一整个雨季
一整个雨季 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:25

    A nice, functional solution, without creating temporary vectors, lists, and so on:

    def everyNth[T](xs: List[T], n:Int): List[T] = xs match {
      case hd::tl => hd::everyNth(tl.drop(n-1), n)
      case Nil => Nil
    }
    

提交回复
热议问题