gpt4 book ai didi

collections - Clojure 中的序列和集合有什么区别

转载 作者:行者123 更新时间:2023-12-03 00:58:38 25 4
gpt4 key购买 nike

我是一名 Java 程序员,也是 Clojure 的新手。从不同的地方,我看到序列和集合在不同的情况下使用。但是,我不知道它们之间的确切区别是什么。

举一些例子:

1) 在 Clojure 的文档中 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 接口(interface)时,前两个函数(first/rest)使用 coll ,这似乎表明这是一个集合,而 cons函数使用 seq 这似乎表明这是一个序列。

2) 有名为 coll?seq? 的函数可用于测试值是集合还是序列。显然集合和顺序是不同的。

3) 在 Clojure 的文档中关于 ' Collections ”,据说:

Because collections support the seq function, all of the sequence functions can be used with any collection

这是否意味着所有集合都是序列?

(coll? [1 2 3]) ; => true 
(seq? [1 2 3]) ; => false

上面的代码告诉我事实并非如此,因为 [1 2 3] 是一个集合,但不是一个序列。

我认为这对于 Clojure 来说是一个非常基本的问题,但我找不到一个地方可以清楚地解释它们的区别以及在不同情况下我应该使用哪一个。如有任何评论,我们将不胜感激。

最佳答案

支持核心的任何对象 firstrest功能是 sequence .

许多对象满足此接口(interface),并且每个 Clojure 集合都提供至少一种 seq 对象,用于使用 seq 遍历其内容。功能。

所以:

user> (seq [1 2 3])
(1 2 3)

您可以从 map 创建一个序列对象也是

user> (seq {:a 1 :b 2})
([:a 1] [:b 2])

这就是为什么您可以使用filter , map , formaps sets等等。

因此您可以将许多类似集合的对象视为序列。

这也是为什么许多序列处理函数如 filter调用seq在输入上:

 (defn filter
"Returns a lazy sequence of the items in coll for which
(pred item) returns true. pred must be free of side-effects."
{:added "1.0"
:static true}
([pred coll]
(lazy-seq
(when-let [s (seq coll)]

如果您调用(filter pred 5)

  Don't know how to create ISeq from: java.lang.Long
RT.java:505 clojure.lang.RT.seqFrom
RT.java:486 clojure.lang.RT.seq
core.clj:133 clojure.core/seq
core.clj:2523 clojure.core/filter[fn]

你看到seq调用是这个对象是一个序列验证。

大部分内容都在 Joy of Clojure 中如果您想深入了解,请参阅第 5 章。

关于collections - Clojure 中的序列和集合有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19850730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com