3

如何在 clojure 中有效地添加两个集合?我试着跟着一个。我想知道有没有比这更有效的方法。

(减少#(conj %1 %2) collection01 collection02)

4

2 回答 2

12

这取决于您想要达到的目标。如果你想要的结果是一个指定类型的集合,它包含给定集合的所有元素,那么into是合适的:(into coll1 coll2)返回(type coll1)包含来自coll1and元素的类型集合coll2

另一方面,如果您只想遍历许多集合(即在集合中创建一系列元素),那么使用更有效concat

user> (concat [1 2 3] (list 4 5 6)) 
(1 2 3 4 5 6)
于 2012-07-10T09:41:10.707 回答
8

使用into

user> (into [1 2 3] [4 5 6])
[1 2 3 4 5 6]
user> (doc into)
-------------------------
clojure.core/into
([to from])
  Returns a new coll consisting of to-coll with all of the items of
  from-coll conjoined.
nil
于 2012-07-10T08:23:53.587 回答