liveBook · Manning

Ordered set

As explained in Clojure: The Essential Reference

sorted-set is a Clojure function that creates a set whose elements are maintained according to a comparator-defined ordering.

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

How Clojure: The Essential Reference covers it

How deep it goes
Defines inputs, outputs, exceptions, implementation class, comparator behavior, metadata, and custom tie-breaking examples.
Examples
Uses reverse sorting, custom collection comparators, metadata on duplicate values, and an incrementally updated dictionary.
What it assumes
Assumes basic Clojure collections and comparison while teaching ordered-set construction, comparator contracts, and incomparable-key failures.
What you can do after
Build it from scratch with sorted-set or sorted-set-by, select comparators, preserve ordering during updates, and avoid comparator-induced duplicates.
How it connects
Connects ordered sets with hash-set, comparators, contains?, subseq, conj, into, and set operations.

Also explained in

Compare how 3 books explain ordered set →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.