在Clojure中序列和集合之间有什么区别 [英] What's the difference between a sequence and a collection in Clojure
问题描述
我是一个Java程序员,是Clojure的新人。从不同的地方,我看到序列和收集在不同的情况下使用。但是,我不知道他们之间的确切差异。
I am a Java programmer and am new to Clojure. From different places, I saw sequence and collection are used in different cases. However, I have no idea what the exact difference is between them.
对于一些示例:
1)在Clojure的文档中, Sequence :
1) In Clojure's documentation for Sequence:
The Seq interface
(first coll)
Returns the first item in the collection.
Calls seq on its argument. If coll is nil, returns nil.
(rest coll)
Returns a sequence of the items after the first. Calls seq on its argument.
If there are no more items, returns a logical sequence for which seq returns nil.
(cons item seq)
Returns a new seq where item is the first element and seq is the rest.
正如你所看到的,当描述Seq接口时,前两个函数'coll'这似乎表明这是一个集合,而'cons'函数使用'seq',这似乎表明这是一个序列。
As you can see, when describing the Seq interface, the first two functions (first/rest) use 'coll' which seems to indicate this is a collection while the 'cons' function use 'seq' which seems to indicate this is a sequence.
称为coll?和seq?可用于测试值是集合还是序列。
2) There are functions called "coll?" and "seq?" that can be used to test if a value is a collection or a sequence. It is clearly collection and sequence are different.
3) In Clojure's documentation about 'Collections', it is said:
由于集合支持seq函数,所以序列
函数可用于任何集合
Because collections support the seq function, all of the sequence functions can be used with any collection
这是否意味着所有集合都是序列?
Does this mean all collections are sequences?
(coll? [1 2 3]) ; => true
(seq? [1 2 3]) ; => false
上面的代码告诉我这不是这种情况,因为[1 2 3]不是一个序列。
The code above tells me it is not such case because [1 2 3] is a collection but is not a sequence.
我认为这是一个很基本的问题Clojure,但我不能找到一个地方解释清楚他们的区别是什么,我在不同的情况下使用。
I think this is a pretty basic question for Clojure but I am not able to find a place explaining this clearly what their difference is and which one should I use in different cases. Any comment is appreciated.
推荐答案
每个序列都是一个集合,但不是每个集合都是序列。
Every sequence is a collection, but not every collection is a sequence.
seq
函数可以转换序列中的集合。例如。对于地图,您会得到其条目的列表。该列表条目与地图本身不同。
The seq
function makes it possible to convert a collection in a sequence. E.g. for a map you get a list of its entries. That list of entries is different from the map itself, though.
这篇关于在Clojure中序列和集合之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!