(Scala)用循环获取当前产量迭代的索引?

时间:2018-06-13 00:38:26

标签: scala for-loop indexing

我遇到了这个问题,我不知道如何解决......我有一个方形的文字。例如:

x xxxx
xxx xx
x xxxx
xx xxx

我想获得每条水平线和垂直线,并将坐标分配到它们的起始位置,从左到右从上到下(左上角为(0; 0))。但是,在Scala中,当我在我的代码中使用for循环时,似乎很简单,我没有当前的迭代索引(就像foreach在c#中没有索引)。这些错误让我在函数式编程过程中陷入困境(我来自OOP背景,所以,你知道:)有时令人沮丧......)

val verticalWords = for(i <- verticalData) yield {



    //<---------- Here is where i need to know current iterations index.
    //If i had current index i could easily set get coordinates by indexes.
    //How do i get current index here?



    val currentWords = i.split(" ").filter(_.length > 0)
    val objWords = for(c <- currentWords) yield {
        Word(Orientation.VERTICAL, c.toString)
    }

    objWords //Array of words
}

- 非常感谢你!

1 个答案:

答案 0 :(得分:3)

您最有可能希望使用zipWithIndex。一个例子:

val text = "abc\ndef\nghi"
val lines = text.split("\n")
for ((line, rowIdx) <- lines.zipWithIndex) {
  for ((character, colIdx) <- line.zipWithIndex) {
    println(character + " at " + (rowIdx, colIdx))
  }
}

输出:

a at (0,0)
b at (0,1)
c at (0,2)
d at (1,0)
e at (1,1)
f at (1,2)
g at (2,0)
h at (2,1)
i at (2,2)