liveBook · Manning

Compare

As explained in Clojure: The Essential Reference

compare is a Clojure function that returns a negative, zero, or positive integer indicating the relative order of two comparable values.

`compare` returns a negative integer when its first value sorts before the second, zero when they compare the same, and a positive integer when the first sorts after the second. Unlike `<` or `>`, it supplies all three outcomes in one result. It is Clojure’s default comparator for `sort` and `sort-by`. section 6.4

Branch on relative order

```clojure (let [c (compare 1 2)] (cond (neg? c) "less than" (zero? c) "equal" (pos? c) "greater than")) ;; => "less than" ``` Test the sign, not an exact return value: `(compare "a" "z")` returns `-25`, not `-1`. section 6.4

The inputs determine which ordering rules apply:

  • `nil` can be compared with other values; `(compare nil (/ -1. 0))` is negative. section 6.4
  • Numbers can be compared with numbers. Other values generally need a compatible `java.lang.Comparable` implementation; an unsupported comparison can throw `ClassCastException`. section 6.4
  • Vectors compare length before elements: `(compare [1 1 1 1] [2 2 2])` is positive. Equal-length vectors can differ at the first unequal element. section 6.4
  • `Double/NaN` compares as zero against the numeric examples shown, so treating that result as an ordinary ordering can produce surprising sorts. section 6.4

Use comparison predicates when a true-or-false condition is enough. Use `compare` when the three-way result matters, including as the ordering supplied to sorting. A custom type can participate by implementing `Comparable` and defining `compareTo`. section 6.3 section 6.4

How Clojure: The Essential Reference covers it

How deep it goes
Details the return contract, eligible inputs, type-specific behavior, edge cases, and performance profiles.
Examples
Uses three-way branching, vector and string comparisons, a sortable custom record, and surprising `NaN` sorting results.
What it assumes
Assumes basic Clojure calls and sorting; introduces the `Comparable` and `compareTo` requirements for custom ordering.
What you can do after
Apply it via Clojure’s `sort` and `sort-by`, or use its sign to choose among three ordering outcomes.
How it connects
Connects comparison predicates, `sort`, `sort-by`, and Java’s `Comparable` interface.

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.