[英]Different return type when I switch for-loop generator order
I have issue with these lines from the book "Scala for the Impatient", which I confirmed myself: 我对《 Scala for the Im耐心》一书的这些说法有疑问,我确认自己:
for (c <- "Hello"; i <- 0 to 1) yield (c + i).toChar
// Yields "HIeflmlmop"
for (i <- 0 to 1; c <- "Hello") yield (c + i).toChar
// Yields Vector('H', 'e', 'l', 'l', 'o', 'I', 'f', 'm', 'm', 'p')
The first yields a String
and the second yields a Vector
? 第一个产生String
,第二个产生Vector
? Yet I would expect them to return the same value. 但是我希望它们返回相同的值。
In general the firs collection in the for comprehension determines the return type of yield
. 通常,for理解中的fir集合确定yield
的返回类型。
Because: 因为:
In scala a for comprehension is syntactic sugar for Collection
.map
, .flatMap
and so on. 在scala中,用于理解的是Collection
.map
, .flatMap
等的语法糖。 So the collection you start with is the collection you end up with. 因此,您开始使用的集合就是您最终使用的集合。
The equivalent with map
and flatMap
for your code would be: 代码中的map
和flatMap
等效于:
"Hello".flatMap(c => (0 to 1).map(i => (c + i).toChar))
or 要么
(0 to 1).flatMap(i => "Hello".map(c => (c + i).toChar))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.