Scala:为什么地图上的“for"理解有时会产生一个列表?
为什么在下面的代码示例中,isAList
的 for
推导式生成一个 List,而其他两个生成 Maps?我想不出任何原因——唯一的区别似乎是 isAList
的推导式声明了两个变量,而其他的则声明了一个或零.
Why, in the below code example, does isAList
's for
comprehension yield a List, but the other two yield Maps? I can't think of any reason - the only difference seems to be that there is isAList
's comprehension declares two variables, and the others declare one or zero.
object Weird {
def theMap: Map[Int, String] =
Map(1 -> "uno", 2 -> "dos", 3 -> "tres")
def main(args: Array[String]) {
val isAMap = for {
(key, value) <- theMap
} yield (key*2 -> value*2)
val isAlsoAMap = for {
(key, value) <- theMap
doubleKey = key*2
} yield (doubleKey -> value*2)
val isAList = for {
(key, value) <- theMap
doubleKey = key*2
doubleValue = value*2
} yield (doubleKey -> doubleValue)
println(isAMap)
println(isAlsoAMap)
println(isAList)
}
}
输出
Map(2 -> unouno, 4 -> dosdos, 6 -> trestres)
Map(2 -> unouno, 4 -> dosdos, 6 -> trestres)
List((2,unouno), (4,dosdos), (6,trestres))
我对 Scala 比较陌生,如果我对某些事情太天真了,请道歉!
I am comparatively new to Scala, so apologies if I'm being incredibly naive about something!
最近关于 ML 的讨论:
Recently discussed on the ML:
https://groups.google.com/forum/#!msg/scala-internals/Cmh0Co9xcMs/D-jr9ULOUISJ
https://issues.scala-lang.org/browse/SI-7515
建议的解决方法是使用元组来传播变量.
Suggested workaround is to use a tuple to propagate the variables.
scala> for ((k,v) <- theMap; (dk,dv) = (k*2,v*2)) yield (dk,dv)
res8: scala.collection.immutable.Map[Int,String] = Map(2 -> unouno, 4 -> dosdos, 6 -> trestres)
更多关于元组机制: