Efficient iteration with index in Scala

前端 未结 12 550
后悔当初
后悔当初 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:22

    Some more ways to iterate:

    scala>  xs.foreach (println) 
    first
    second
    third
    

    foreach, and similar, map, which would return something (the results of the function, which is, for println, Unit, so a List of Units)

    scala> val lens = for (x <- xs) yield (x.length) 
    lens: Array[Int] = Array(5, 6, 5)
    

    work with the elements, not the index

    scala> ("" /: xs) (_ + _) 
    res21: java.lang.String = firstsecondthird
    

    folding

    for(int i=0, j=0; i+j<100; i+=j*2, j+=i+2) {...}
    

    can be done with recursion:

    def ijIter (i: Int = 0, j: Int = 0, carry: Int = 0) : Int =
      if (i + j >= 100) carry else 
        ijIter (i+2*j, j+i+2, carry / 3 + 2 * i - 4 * j + 10) 
    

    The carry-part is just some example, to do something with i and j. It needn't be an Int.

    for simpler stuff, closer to usual for-loops:

    scala> (1 until 4)
    res43: scala.collection.immutable.Range with scala.collection.immutable.Range.ByOne = Range(1, 2, 3)
    
    scala> (0 to 8 by 2)   
    res44: scala.collection.immutable.Range = Range(0, 2, 4, 6, 8)
    
    scala> (26 to 13 by -3)
    res45: scala.collection.immutable.Range = Range(26, 23, 20, 17, 14)
    

    or without order:

    List (1, 3, 2, 5, 9, 7).foreach (print) 
    

提交回复
热议问题