Clojure 中的序列和集合有什么区别 [英] What's the difference between a sequence and a collection in Clojure
问题描述
我是一名 Java 程序员,我是 Clojure 的新手.从不同的地方,我看到序列和集合用于不同的情况.但是,我不知道它们之间的确切区别是什么.
举几个例子:
1) 在 Clojure 的 Sequence 文档中:
Seq 接口(第一个)返回集合中的第一项.根据其参数调用 seq.如果 coll 为 nil,则返回 nil.(休息科尔)返回第一个之后的项目序列.根据其参数调用 seq.如果没有更多项,则返回一个逻辑序列,seq 返回 nil.(缺点项目序列)返回一个新的 seq,其中 item 是第一个元素,seq 是其余元素.
如您所见,在描述 Seq 接口时,前两个函数(first/rest)使用了 coll
似乎表明这是一个集合,而 cons
函数使用 seq
这似乎表明这是一个序列.
2) 有名为 coll?
和 seq?
的函数可用于测试值是集合还是序列.显然是集合和顺序不同.
3) 在 Clojure 的关于Collections"的文档中,是这样说的:><块引用>
因为collections支持seq函数,所有的sequence函数可用于任何集合
这是否意味着所有集合都是序列?
(coll? [1 2 3]) ;=>真的(seq? [1 2 3]) ;=>错误的
上面的代码告诉我事实并非如此,因为 [1 2 3]
是一个集合而不是一个序列.
我认为这是 Clojure 的一个非常基本的问题,但我找不到一个地方来清楚地解释它们的区别以及在不同情况下我应该使用哪个.任何意见表示赞赏.
每个序列都是一个集合,但并不是每个集合都是一个序列.
seq
函数可以将集合转换为序列.例如.对于地图,您将获得其条目的列表.不过,该条目列表与地图本身不同.
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.
For some examples:
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.
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.
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:
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
The code above tells me it is not such case because [1 2 3]
is a collection but is not a sequence.
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.
The seq
function makes it possible to convert a collection into 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屋!