与 Clojure 的序列不一致? [英] Inconsistency with Clojure's sequences?
问题描述
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?
推荐答案
conj
的文档(来自 clojure.org):
conj[oin].返回一个带有 xs 的新集合'添加'.(conj nil item) 返回 (item).添加"可能发生在不同的地方",具体取决于具体类型.
conj[oin]. Returns a new collection with the xs 'added'. (conj nil item) returns (item). The 'addition' may happen at different 'places' depending on the concrete type.
将元素添加"到向量的末尾更有效,而在列表的开头这样做更有效.conj
使用最有效的数据结构.
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.
在你给出的例子中,'(1 2 3)
和 (seq [1 2 3])
都实现了 ISeq
(见seq?
的文档),而 [1 2 3]
没有.
In the examples you give, '(1 2 3)
and (seq [1 2 3])
both implement ISeq
(see documentation for seq?
), while [1 2 3]
doesn't.
Clojure 的 conj
最终会在底层数据结构;对于向量 (PersistentVector
),cons
将元素添加到末尾,而对于列表,它们被添加到前面(cons
方法用于 PersistentList
s 返回一个新列表,以新元素为头,现有列表为尾.
Clojure's conj
ultimately calls the cons
method (not to be confused with the cons
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 (the cons
method for PersistentList
s returns a new list with the new element as its head, and the existing list as its tail).
这篇关于与 Clojure 的序列不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!