cons
传统上指将第一个参数添加到第二个参数之前构造新对象,这就是参数的顺序。
以下是来自 LISP cons 的引用:
在 LISP 术语中,“将 x 添加到 y” 表示通过 (cons x y)
构造一个新对象
但是 conjoin
通常是在给定数据结构上附加的操作,具体取决于你使用的 clojure 数据类型。这就是为什么集合首先出现,然后是要附加的元素。
让我们看看 Vector
;
user=> (type [3 5 7 11])
clojure.lang.PersistentVector
user=> (cons 1 [3 5 7 11])
(1 3 5 7 11)
user=> (conj [3 5 7 11] 13)
[3 5 7 11 13]
但对于List
,conjoin
也会在前面添加元素,
user=> (type '(3 5 7 11))
clojure.lang.PersistentList
user=> (cons 1 '(3 5 7 11))
(1 3 5 7 11)
user=> (conj '(3 5 7 11) 13)
(13 3 5 7 11)
conj的文档也有相关说明。
user=> (doc conj)
-------------------------
clojure.core/conj
([coll x] [coll x & xs])
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.
nil
该命令适用于我所知道的任何其他函数式语言。以下是在Scala中的示例:
scala> 1 +: Seq(1, 3, 5)
res1: Seq[Int] = List(1, 1, 3, 5)
scala> Seq(1, 3, 5) :+ 7
res2: Seq[Int] = List(1, 3, 5, 7)
conj
很像一个操作,即数据类型需要支持它。另一方面,cons
并不操作 seq,它可以接受任何可序列化的东西。也就是说,您可以执行(cons 1 "abc")
或(cons 1 (into-array [1 2]))
。 - ClojureMostly