liveBook · Manning

Sorted-map-by

As explained in Clojure: The Essential Reference

sorted-map-by is a Clojure constructor function that creates a persistent map whose keys are ordered by a supplied comparator.

sorted-map-by constructs a persistent map whose keys follow a supplied two-argument comparator. Provide the comparator first, then an even number of key/value arguments; the result is a PersistentTreeMap. section 11.1.3

Order keys by a field

(sorted-map-by #(< (:age %1) (:age %2)) {:age 35} ["J" "K"] {:age 13} ["Q" "R"] {:age 14} ["T" "V"]) ;; {{:age 13} ["Q" "R"], {:age 14} ["T" "V"], {:age 35} ["J" "K"]}

Keep these behavioral details in mind:

  • The comparator returns a negative, zero, or positive number for less-than, equality, or greater-than ordering. section 11.1.3
  • Odd key/value arity throws IllegalArgumentException; incomparable or incompatible key types can throw ClassCastException. section 11.1.3

Use ordered maps in algorithms

A sorted map can act as a priority queue. An A* implementation initializes its frontier with (sorted-map-by compare [0 orig] [[] 0]) and repeatedly processes the lowest-scored entry. section 11.1.3

How Clojure: The Essential Reference covers it

How deep it goes
Explains inputs, outputs, exceptions, comparator equality, metadata retention, and practical examples, but not tree implementation internals.
Examples
Demonstrates age ordering, length-based ordering with tie-breakers, metadata retention, and an A* route search.
What it assumes
Assumes basic Clojure map construction and key/value pairs; teaches comparator results and key comparability requirements.
What you can do after
Build it from scratch by supplying comparators, constructing ordered maps, and avoiding accidental key collapse.
How it connects
Connects persistent maps, comparators, priority queues, and the A* algorithm.

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.