scala 由 for 生成的带产量的集合类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2947896/
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
Collection type generated by for with yield
提问by Jesper
When I evaluate a forin Scala, I get an immutable IndexedSeq(a collection with array-like performance characteristics, such as efficient random access):
当我for在 Scala 中评估 a时,我得到一个不可变的IndexedSeq(具有类似数组的性能特征的集合,例如高效的随机访问):
scala> val s = for (i <- 0 to 9) yield math.random + i
s: scala.collection.immutable.IndexedSeq[Double] = Vector(0.6127056766832756, 1.7137598183155291, ...
Does a forwith a yieldalways return an IndexedSeq, or can it also return some other type of collection class (a LinearSeq, for example)? If it can also return something else, then what determines the return type, and how can I influence it?
做了for一个yield始终返回IndexedSeq,或者它也返回一些其他类型的集合类(A LinearSeq,例如)?如果它也可以返回其他东西,那么是什么决定了返回类型,我如何影响它?
I'm using Scala 2.8.0.RC3.
我正在使用 Scala 2.8.0.RC3。
采纳答案by Jesper
Thanks michael.kebe for your comment.
感谢 michael.kebe 的评论。
Thisexplains how foris translated to operations with map, flatMap, filterand foreach. So my example:
这解释了如何for转换为与操作map,flatMap,filter和foreach。所以我的例子:
val s = for (i <- 0 to 9) yield math.random + i
is translated to something like this (I'm not sure if it's translated to mapor flatMapin this case):
被翻译成这样的东西(我不确定它是否被翻译成map或flatMap在这种情况下):
val s = (0 to 9) map { math.random + _ }
The result type of operations like mapon collections depends on the collection you call it on. The type of 0 to 9is a Range.Inclusive:
map集合操作的结果类型取决于您调用它的集合。的类型0 to 9是Range.Inclusive:
scala> val d = 0 to 9
d: scala.collection.immutable.Range.Inclusive with scala.collection.immutable.Range.ByOne = Range(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
The result of the mapoperation on that is an IndexedSeq(because of the builder stuff inside the collections library).
操作的结果map是IndexedSeq(因为集合库中的构建器内容)。
So, to answer my question: the result of a for (...) yield ...depends on what type is inside the parantheses. If I want a Listas the result, I could do this:
所以,回答我的问题: a 的结果for (...) yield ...取决于括号内的类型。如果我想要一个List结果,我可以这样做:
scala> val s = for (i <- List.range(0, 9)) yield math.random + i
s: List[Double] = List(0.05778968639862214, 1.6758775042995566, ...
回答by thSoft
You can always transform a range to a list using toList:
您始终可以使用 toList 将范围转换为列表:
> val s = for (i <- (0 to 9).toList) yield math.random + i
> s : List[Double]

