如何在Clojure中将列表或向量转换为排序集?

11
在Clojure中,set函数会自动将vectorlist转换为set。但对于sorted-set函数则不是这样的情况。
(set [3 2 1])  ; #{1 2 3}
(set '(3 2 1)) ; #{1 2 3}
(sorted-set [3 2 1])  ; #{[3 2 1]}
(sorted-set '(3 2 1)) ; #{(3 2 1)}

这是我想出来的解决方案:

(defn sorted-set-from-coll [coll]
    (eval (cons sorted-set (seq coll))))

(def v [3 2 1])
(sorted-set-from-coll v)        ; #{1 2 3}
(sorted-set-from-coll '(3 2 1)) ; #{1 2 3}
(sorted-set-from-coll [3 1 2])  ; #{1 2 3}

有没有更好、更符合惯用法的方法来实现这个需求,而不需要使用eval?

2个回答

19

into 在这种情况下也非常有用。

user=> (into (sorted-set) [3 1 2])
#{1 2 3}

9

您可以使用apply来实现:

user=> (apply sorted-set [3 1 2])
#{1 2 3}

4
"into"更符合惯用语,因为它能够传达正在发生的事情(一个数据结构转换为另一个),并且可以与现有的目标数据结构一起使用。 - Alex Taggart

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接