Scala filter on a list by index

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

    Clojure has a take-nth function that does what you want, but I was surprised to find that there's not an equivalent method in Scala. You could code up a similar recursive solution based off the Clojure code, or you could read this blog post:

    Scala collections: Filtering each n-th element

    The author actually has a nice graph at the end showing the relative performance of each of his solutions.

提交回复
热议问题