【问题标题】:Add two collections in clojure在clojure中添加两个集合
【发布时间】:2012-07-10 19:01:22
【问题描述】:

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

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

【问题讨论】:

  • 不是您问题的答案,但 reduce 函数可能只是 conj; reduce 使用两个参数调用它,因此 #(conj %1 %2)conj 在功能上是等效的。

标签: clojure functional-programming


【解决方案1】:

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

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

user> (concat [1 2 3] (list 4 5 6)) 
(1 2 3 4 5 6)

【讨论】:

    【解决方案2】:

    使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-03
      • 2015-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      相关资源
      最近更新 更多