为什么在地图操作后范围会转换为向量? [英] Why is a Range transformed to a Vector after map operation?

查看:32
本文介绍了为什么在地图操作后范围会转换为向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Coursera 上的 Scala 课程之后,Martin Odersky 展示了一个示例代码:

Following Scala courses on Coursera, Martin Odersky showed an example code which is:

1 to 5 map ( i => i*i )

他说 Range 被转换为 Vector 因为它们共享相同的接口 (IndexedSeq) 并且结果无法表示作为 Range(在它的例子中更清楚,因为他生成了一个不能表示为 Range 的对).

And he said the Range gets transformed to a Vector because they share the same interface (IndexedSeq) and the result could not be represented as a Range (it was more clear in its example since he generated a pair which is not representable as a Range).

我不确定是否理解,因为我认为他之前说过,在 for 表达式中,第一个生成器将确定将产生的元素类型,并且似乎并不总是正确的,至少对于 Range.

I'm not sure to understand because I think he said previously that in a for expression the 1st generator will determine the kind of element that will be yielded, and it seems not always true, at least for Range.

而且我不确定为什么输出是 Vector,因为 Vector 可能不是唯一可以表示上述计算结果的另一种实现.

And I'm not sure to understand why the output is Vector, because Vector may not be the only other one implementation that can represent the result computed above.

有人可以帮我理解这部分吗?

Can someone help me understand this part please?

推荐答案

map 暗中将 CanBuildFrom 作为隐式参数.它的工作是根据您已经拥有的集合(以及内容的类型)生成一个新集合.由于Range 不能包含任意内容——甚至不能包含任意整数——因此没有产生RangeCanBuildFrom.具有 CanBuildFromRange 最具体的超类型是 IndexedSeq.由它实际构建的集合是一个Vector.

map secretly takes a CanBuildFrom as an implicit argument. Its job is to produce a new collection given the one you've already got (and the type of the contents). Since Range can't contain arbitrary stuff--not even arbitrary integers--there is no CanBuildFrom that produces a Range. The most specific supertype of Range that does have a CanBuildFrom is IndexedSeq. The collection that is actually built by this is a Vector.

这篇关于为什么在地图操作后范围会转换为向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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