Efficient iteration with index in Scala

前端 未结 12 554
后悔当初
后悔当初 2020-12-12 11:57

Since Scala does not have old Java style for loops with index,

// does not work
val xs = Array(\"first\", \"second\", \"third\")
for (i=0; i<         


        
12条回答
  •  温柔的废话
    2020-12-12 12:11

    There's nothing in the stdlib that will do it for you without creating tuple garbage, but it's not too hard to write your own. Unfortunately I've never bothered to figure out how to do the proper CanBuildFrom implicit raindance to make such things generic in the type of collection they're applied to, but if it's possible, I'm sure someone will enlighten us. :)

    def foreachWithIndex[A](as: Traversable[A])(f: (Int,A) => Unit) {
      var i = 0
      for (a <- as) {
        f(i, a)
        i += 1
      }
    }
    
    def mapWithIndex[A,B](in: List[A])(f: (Int,A) => B): List[B] = {
      def mapWithIndex0(in: List[A], gotSoFar: List[B], i: Int): List[B] = {
        in match {
          case Nil         => gotSoFar.reverse
          case one :: more => mapWithIndex0(more, f(i, one) :: gotSoFar, i+1)
        }
      }
      mapWithIndex0(in, Nil, 0)
    }
    
    // Tests....
    
    @Test
    def testForeachWithIndex() {
      var out = List[Int]()
      ScalaUtils.foreachWithIndex(List(1,2,3,4)) { (i, num) =>
        out :+= i * num
      }
      assertEquals(List(0,2,6,12),out)
    }
    
    @Test
    def testMapWithIndex() {
      val out = ScalaUtils.mapWithIndex(List(4,3,2,1)) { (i, num) =>
        i * num
      }
    
      assertEquals(List(0,3,4,3),out)
    }
    

提交回复
热议问题