scala中 ‘<-’ 与 for
for (i <- 1 to 3; from = 4 - i; j <- from to 3) {
println((10 * i + j));
println(from);
}
执行结果如下
13
3
22
2
23
2
31
1
32
1
33
1
从执行结果中可以看出,for在做笛卡尔积,简单来说就是前面的每一个要对应后面的全部,赋值语句被当作只有一个,以‘;’为界,从前向后依次对应
<-总是被当成小于负的xxx,很奇怪的发明,感觉好像用in更好。
for (c <- "Hello"; i <- 0 to 1) yield (c + i).toChar
for (i <- 0 to 1; c <- "Hello") yield (c + i).toChar
"a"+1
1+"a"
执行结果如下
res8: String = HIeflmlmop
res9: scala.collection.immutable.IndexedSeq[Char] = Vector(H, e, l, l, o, I, f, m, m, p)
res10: String = a1
res11: String = 1a
for推导式当存在2个遍历对象时,如同外层循环套着内层循环,yield似乎只注重最外圈的循环,并试图与最外圈的循环类型保持一致