Skip to content

clojure.core/compare

View this page on ClojureDocs

Type: function Added: Clojure 1.0 Examples: 9 Runnable: 3
([x y])

Comparator. Returns a negative number, zero, or a positive number when x is logically 'less than', 'equal to', or 'greater than' y. Same as Java x.compareTo(y) except it also works for nil, and compares numbers and collections in a type-independent manner. x must implement Comparable

Examples

by shockbob on
by nwallace on
by ercliou on . May have evaluation errors.
by jafingerhut on . May have evaluation errors.
by jafingerhut on . May have evaluation errors.
by jafingerhut on . May have evaluation errors.
by jafingerhut on . May have evaluation errors.
by jafingerhut on . May have evaluation errors.
by uosl on

Note by glts

It is clear what compare does, but how do you turn its output into an answer to questions like ‘is x less than y’ or ‘is x greater than or equal to y’?

While the numeric < <= = >= > provide that answer in Boolean form right away, with compare a second step is required.

((juxt < <= = >= >) 2 3)
;;=> [true true false false false]

Here is a listing of the same relations using compare:

((juxt (comp neg? compare)
       (comp not pos? compare)
       (comp zero? compare)
       (comp not neg? compare)
       (comp pos? compare))
 "2" "3")
;;=> [true true false false false]

See also


Content from the matching ClojureDocs page, with authors credited on each contribution.