与 Clojure 的序列不一致?
Clojure:
1:13 user=> (first (conj '(1 2 3) 4))
4
1:14 user=> (first (conj [1 2 3] 4))
1
; . . .
1:17 user=> (first (conj (seq [1 2 3]) 4))
4
我明白发生了什么,但是这应该以不同的方式工作吗?
Clojure:
1:13 user=> (first (conj '(1 2 3) 4))
4
1:14 user=> (first (conj [1 2 3] 4))
1
; . . .
1:17 user=> (first (conj (seq [1 2 3]) 4))
4
I understand what is going on, but should this work differently?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
conj
的文档(来自 clojure.org):将元素“添加”到向量的末尾更有效,而在列表的开头这样做更有效。
conj
使用对于您提供的数据结构来说最有效的任何内容。在您给出的示例中,
'(1 2 3)
和(seq [1 2 3])
都实现了ISeq
(请参阅seq?
的文档),而[1 2 3]
没有。Clojure 的 conj 最终调用底层数据结构上的 cons 方法(不要与 cons 函数混淆 - 该方法是内部 clojure 代码) ;对于向量 (
PersistentVector
),cons
将元素添加到末尾,而对于列表,它们将添加到前面(cons
方法用于 < code>PersistentLists 返回一个新列表,其中新元素作为其头部,现有列表作为其尾部)。Documentation for
conj
(from clojure.org):It's more efficient to "add" elements to the end of a vector, while it's more efficient to do so at the beginning of lists.
conj
uses whatever is the most efficient for the data structure you give it.In the examples you give,
'(1 2 3)
and(seq [1 2 3])
both implementISeq
(see documentation forseq?
), while[1 2 3]
doesn't.Clojure's
conj
ultimately calls thecons
method (not to be confused with thecons
function - this method is internal clojure code) on the underlying data structure; for vectors (PersistentVector
),cons
adds elements to the end, while for lists they're added to the front (thecons
method forPersistentList
s returns a new list with the new element as its head, and the existing list as its tail).如果您查看 Clojure 数据结构,
您会发现 conj 对于列表和向量的工作方式有所不同。
conj 将添加的项目放在列表的前面和向量的末尾。
我还建议查看 Clojure API conj
其中有一些很好的示例。 ClojureDocs 总体上为大多数 Clojure 命令提供了一些非常好的示例。
If you look at Clojure Data Structures
you'll see that conj works differently with lists and vectors.
conj puts the added item at the front of the list and at the end of a vector.
I also suggest looking at Clojure API conj
which has some nice examples. ClojureDocs overall has some very nice examples for most Clojure commands.