Scala filter on a list by index

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

    I would do it like in Octave mathematical program.

    val indices = 0 until n by 3  // Range 0,3,6,9 ...
    

    and then I needed some way to select the indices from a collection. Obviously I had to have a collection with random-access O(1). Like Array or Vector. For example here I use Vector. To wrap the access into a nice DSL I'd add an implicit class:

    implicit class VectorEnrichedWithIndices[T](v:Vector[T]) {
      def apply(indices:TraversableOnce[Int]):Vector[T] = {
        // some implementation 
        indices.toVector.map(v)
      }
    }
    

    The usage would look like:

    val vector = list.toVector
    val every3rdElement = vector(0 until vector.size by 3)
    

提交回复
热议问题