An ordered set stores unique elements while maintaining their order through a comparator. Clojure provides sorted-set with the default comparator and sorted-set-by for an explicitly supplied comparator. section 13.0 section 13.3
The core contract is:
- Pass any number of keys to sorted-set, or pass a comparator followed by keys to sorted-set-by. section 13.3
- Receive a PersistentTreeSet containing distinct keys, returned in comparator order when iterated. section 13.3
- Expect ClassCastException when keys cannot be compared; unlike hash-set, ordered sets have no transient version. section 13.3
- Use ordered sets when incremental updates should preserve order, avoiding a separate sort after each insertion. section 13.3
Default and reverse ordering
(sorted-set "t" "d" "j" "w" "y") ;; #{"d" "j" "t" "w" "y"} (sorted-set-by #(compare %2 %1) "t" "d" "j" "w" "y") ;; #{"y" "w" "t" "j" "d"}
Make comparator ties distinct
A comparator that considers only collection length collapses equal-length collections into one set entry. Add a secondary comparison to retain all distinct values: (sorted-set-by (fn [a b] (compare [(count b) a] [(count a) b])) [1 :a] [:b] [3 :c] [:v]) ;; #{[1 :a] [3 :c] [:b] [:v]}


