Scala Traversable、Iterable、Sequence、Stream 和 View 的语义? [英] Semantics of Scala Traversable, Iterable, Sequence, Stream and View?

查看:49
本文介绍了Scala Traversable、Iterable、Sequence、Stream 和 View 的语义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还有其他问题,例如Scala:Scala 集合中的 Traversable 和 Iterable trait 有什么区别?如何在 Scala 中获得两个列表的平方和? 部分回答了这个问题.我觉得在一个地方涵盖所有这些的问题是有道理的.

There are other questions such as Scala: What is the difference between Traversable and Iterable traits in Scala collections? and How would I get the sum of squares of two Lists in Scala? that answers the question partially. I felt a question that covers all of this in one place makes sense.

推荐答案

Traversable 是集合层次结构的顶部.它的主要方法是foreach",因此它允许为集合的每个元素做一些事情.

Traversable is the top of the collections hierarchy. Its main method is 'foreach' so it allows to do something for each element of the collection.

Iterable 可以创建迭代器,基于它可以实现 foreach.这定义了元素的某些顺序,尽管该顺序可能会因每个迭代器而改变.

An Iterable can create an Iterator, based on which foreach can be implemented. This defines some order of the elements, although that order might change for every Iterator.

Seq(uence) 是一个 Iterable,其中元素的顺序是固定的.因此,讨论元素的索引是有意义的.

Seq(uence) is an Iterable where the order of elements is fixed. Therefore it makes sense to talk about the index of an element.

Streams 是惰性序列.IE.流的元素在被访问之前可能不会被计算.这使得处理无限序列(如所有整数的序列)成为可能.

Streams are lazy Sequences. I.e. elements of a stream may not be computed before they are accessed. This makes it possible to work with infinite sequences like the sequence of all integers.

视图是集合的非严格版本.视图上的过滤器和映射等方法仅在访问相应元素时执行传递的函数.因此,巨大集合上的映射会立即返回,因为它只是在原始集合周围创建了一个包装器.只有当访问一个元素时,映射才会实际执行(针对该元素).请注意,View 不是一个类,但是有很多 XxxView 类用于各种集合.

Views are non-strict versions of collections. Methods like filter and map on view only execute the passed functions when the respective element gets accessed. Thus a map on a huge collection returns immediately because it just creates a wrapper around the original collection. Only when one accesses an element, the mapping gets actually executed (for that element). Note that View is not a class, but there are lots of XxxView classes for various collections.

这篇关于Scala Traversable、Iterable、Sequence、Stream 和 View 的语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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