我想知道for-yield块中的scala中的控制流。我看到所有元素都首先通过' for'部分后跟' yield'部分。这是为什么?如果它不是for-yield for element1,for-yield for element2 ......
scala> val list = List(1,2,3,4,5,6)
list: List[Int] = List(1, 2, 3, 4, 5, 6)
scala> :paste
// Entering paste mode (ctrl-D to finish)
val t = for {
i <- list
log = println("processing " + i)
} yield {
println("In yield for " + i)
i
}
// Exiting paste mode, now interpreting.
processing 1 //All of them first go through the for block
processing 2
processing 3
processing 4
processing 5
processing 6
In yield for 1 // yield comes after all
In yield for 2
In yield for 3
In yield for 4
In yield for 5
In yield for 6
t: List[Int] = List(1, 2, 3, 4, 5, 6)
答案 0 :(得分:3)
您的代码
val t = for {
i <- list
log = println("processing " + i)
} yield {
println("In yield for " + i)
i
}
粗略地贬低
val t = list.map { i =>
val log = println("processing " + i)
(i, log)
}.map { x =>
x match {
case (i, log) =>
println("In yield for " + i)
}
}
从这里你可以看到为什么你首先得到所有“处理...”消息。