liveBook · Manning

Sorted-set-by

As explained in Clojure: The Essential Reference

sorted-set-by is a Clojure constructor function that creates a sorted set using a supplied comparator.

sorted-set-by constructs an ordered set from a comparator followed by any number of keys. Iteration follows comparator order, while duplicate keys are omitted. section 13.3

Use the constructor with these practical rules:

  • Pass any object implementing java.util.Comparator; ordinary Clojure comparison functions such as <, >, >=, and <= can serve as comparators. section 13.3
  • Expect a PersistentTreeSet containing distinct keys; iteration uses the supplied comparator rather than the default ordering. section 13.3
  • Avoid incomparable key pairs, which can raise ClassCastException; different numeric types remain comparable. section 13.3

Reverse order and comparator ties

(sorted-set-by #(compare %2 %1) "t" "d" "j" "w" "y") ;; #{"y" "w" "t" "j" "d"} ;; A comparator that compares only lengths drops equal-length values: (sorted-set-by (fn [a b] (compare (count b) (count a))) [1 :a] [:b] [3 :c] [:v]) ;; #{[1 :a] [:b]} ;; Add a tie-breaker when equal lengths must remain distinct.

How Clojure: The Essential Reference covers it

How deep it goes
Defines inputs, output type, ordering, duplicate handling, and incomparable-key exceptions, then demonstrates comparator edge cases.
Examples
Uses reverse string ordering, length-based collection ordering, tie-breakers, and an incrementally updated dictionary.
What you can do after
Build it from scratch by supplying a comparator and keys, then iterate or update the resulting ordered set.
How it connects
Connects sorted sets with comparators, hash sets, sorted-set, sorted-map, and PersistentTreeSet.

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.