11

In Clojure, the set function automatically converts a vector or list into a set. But this is not the case for 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)}

Here is a solution I come up with:

(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}

Is there a better / more idiomatic way to do this without eval?

newtonapple
  • 4,053
  • 2
  • 30
  • 29

2 Answers2

18

into is also quite useful in such cases.

user=> (into (sorted-set) [3 1 2])
#{1 2 3}
kotarak
  • 16,528
  • 2
  • 45
  • 39
9

You can use apply for this:

user=> (apply sorted-set [3 1 2])
#{1 2 3}
Jonas
  • 18,022
  • 9
  • 52
  • 67
  • 3
    `into` is more idiomatic as it both conveys what's happening (one datastructure into another), and can be used with an existing destination datastructure. – Alex Taggart Feb 27 '12 at 17:43