Scala 中的嵌套迭代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3634897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nested iteration in Scala
提问by Wildcat
What is the difference (if any) between two code fragments below?
下面的两个代码片段之间有什么区别(如果有的话)?
Example from Ch7 of Programming i Scala
来自 Programming i Scala 的 Ch7 的示例
def grep(pattern: String) =
for (
file <- filesHere
if file.getName.endsWith(".scala");
line <- fileLines(file)
if line.trim.matches(pattern)
) println(file + ": " + line.trim)
and this one
还有这个
def grep2(pattern: String) =
for (
file <- filesHere
if file.getName.endsWith(".scala")
) for (
line <- fileLines(file)
if line.trim.matches(pattern)
) println(file + ": " + line.trim)
Or
或者
for (i <- 1 to 2)
for (j <- 1 to 2)
println(i, j)
and
和
for (
i <- 1 to 2;
j <- 1 to 2
) println(i, j)
回答by sepp2k
In this case there is no difference. However when using yield there is:
在这种情况下没有区别。但是,在使用 yield 时有:
for (
i <- 1 to 2;
j <- 1 to 2
) yield (i, j)
Will give you a sequence containing (1,1), (1,2), (2,1)and (2,2).
会给你一个包含(1,1), (1,2),(2,1)和的序列(2,2)。
for (i <- 1 to 2)
for (j <- 1 to 2)
yield (i, j)
Will give you nothing, because it generates the sequence (i,1), (i,2)on each iteration and then throws it away.
不会给你任何东西,因为它会在每次迭代中生成序列(i,1),(i,2)然后将其丢弃。
回答by Mishael Rosenthal
Sometimes it is also useful to output a multi dimensional collection (for example a matrix of table):
有时输出多维集合(例如表格矩阵)也很有用:
for (i <- 1 to 2) yield for (j <- 1 to 2) yield (i, j)
Will return:
将返回:
Vector(Vector((1,1), (1,2)), Vector((2,1), (2,2)))

