Scala filter on a list by index

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

    Ah, how about this?

    val l = List(10,9,8,7,6,5,4,3,2,1,0)
    for (i <- (0 to l.size - 1 by 3).toList) yield l(i)
    //res0: List[Int] = List(10, 7, 4, 1)
    

    which can be made more general by

    def seqByN[A](xs: Seq[A], n: Int): Seq[A] = for (i <- 0 to xs.size - 1 by n) yield xs(i)
    
    scala> seqByN(List(10,9,8,7,6,5,4,3,2,1,0), 3)
    res1: Seq[Int] = Vector(10,7,4,1)
    
    scala> seqByN(List(10,9,8,7,6,5,4,3,2,1,0), 3).toList
    res2: Seq[Int] = List(10,7,4,1)
    
    scala> seqByN(List[Int](), 3)
    res1: Seq[Int] = Vector()
    

    But by functional do you mean only using the various List combinator functions? Otherwise, are Streams functional enough?

    def fromByN[A](xs: List[A], n: Int): Stream[A] = if (xs.isEmpty) Stream.empty else
      xs.head #:: fromByN(xs drop n, n)
    
    scala> fromByN(List(10,9,8,7,6,5,4,3,2,1,0), 3).toList
    res17: List[Int] = List(10, 7, 4, 1)
    

提交回复
热议问题