clojure - 与 Clojure 的序列不一致?

标签 clojure seq

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

我了解发生了什么,但这应该以不同的方式工作吗?

最佳答案

conj 的文档(来自 clojure.org ):

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使用对您提供的数据结构最有效的任何东西。

在您给出的示例中,'(1 2 3)(seq [1 2 3])都实现ISeq (见 documentation for seq? ),而 [1 2 3]没有。

Clojure 的 conj最终调用cons底层数据结构上的方法(不要与 cons 函数混淆 - 此方法是内部 clojure 代码);对于向量(PersistentVector),cons将元素添加到末尾,而对于列表,它们被添加到前面(cons s 的 PersistentList 方法返回一个新列表,其中新元素作为其头部,现有列表作为其尾部)。

关于clojure - 与 Clojure 的序列不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7437833/

相关文章:

Clojure - core.async 合并单向 channel

clojure - 在 Clojure 中解释 `(apply partial partial args)`?

list - clojure - 2 个列表的有序成对组合

r - 如何将 for 循环与特殊 seq 一起使用

list - 将 List[Tuple2[A,B]] 转换为 Tuple2[Seq[A],Seq[B]]

session - 通过 SSH session 关闭 - 这可能吗?

asynchronous - Clojure core.async 和 clojure.core 命名空间元素似乎发生了冲突

scala - SortedSet 为保留(排序)顺序的 seq

f# - 在 F# 序列中复制列表项 n 次

r - cumsum is.na rle 忽略 conectives NA