由 for 生成的带产量的集合类型 [英] Collection type generated by for with yield

查看:30
本文介绍了由 for 生成的带产量的集合类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 Scala 中评估 for 时,我得到一个不可变的 IndexedSeq(一个具有类似数组性能特征的集合,例如高效的随机访问):

When I evaluate a for in Scala, I get an immutable IndexedSeq (a collection with array-like performance characteristics, such as efficient random access):

scala> val s = for (i <- 0 to 9) yield math.random + i
s: scala.collection.immutable.IndexedSeq[Double] = Vector(0.6127056766832756, 1.7137598183155291, ...

带有 yieldfor 是否总是返回一个 IndexedSeq,或者它也可以返回一些其他类型的集合类(一个 >LinearSeq,例如)?如果它也可以返回其他东西,那么返回类型由什么决定,我如何影响它?

Does a for with a yield always 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?

我使用的是 Scala 2.8.0.RC3.

I'm using Scala 2.8.0.RC3.

推荐答案

感谢 michael.kebe 的评论.

Thanks michael.kebe for your comment.

解释了如何for被转换为 mapflatMapfilterforeach 的操作.所以我的例子:

This explains how for is translated to operations with map, flatMap, filter and foreach. So my example:

val s = for (i <- 0 to 9) yield math.random + i

被翻译成这样的东西(我不确定在这种情况下它是被翻译成 map 还是 flatMap):

is translated to something like this (I'm not sure if it's translated to map or flatMap in this case):

val s = (0 to 9) map { math.random + _ }

map 等集合操作的结果类型取决于您调用它的集合.0 to 9 的类型是一个 Range.Inclusive:

The result type of operations like map on collections depends on the collection you call it on. The type of 0 to 9 is a 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)

map 操作的结果是一个 IndexedSeq(因为集合库中的构建器内容).

The result of the map operation on that is an IndexedSeq (because of the builder stuff inside the collections library).

所以,回答我的问题:for (...) yield ... 的结果取决于括号内的类型.如果我想要一个 List 作为结果,我可以这样做:

So, to answer my question: the result of a for (...) yield ... depends on what type is inside the parantheses. If I want a List as the result, I could do this:

scala> val s = for (i <- List.range(0, 9)) yield math.random + i
s: List[Double] = List(0.05778968639862214, 1.6758775042995566, ...

这篇关于由 for 生成的带产量的集合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆