compare

added
1.0

ns
clojure.core

type
function

(compare 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

                ;; various examples
;; comparing vectors of different sizes does not work as you may expect
;; the longer vector is always "greater" regardless of contents 

user=> (compare [0 1 2] [0 1 2])
0
user=> (compare [1 2 3] [0 1 2 3])
-1
user=> (compare [0 1 2] [3 4])
1
user=> (compare nil [1 2 3])
-1
user=> (compare [1 2 3] nil)
1
user=>  (compare [2 11] [99 1])
-1
user=> (compare "abc" "def")
-3
user=> (compare "abc" "abd")
-1
            
                ;; number comparisons give results of either 1, 0 or -1
(compare 1 0) ;; => 1
(compare 1 1) ;; => 0
(compare 1 2) ;; => -1
(compare 1 3) ;; => -1

;; string comparisons give results of the distance between the first characters
(compare "B" "A") ;; => 1
(compare "B" "B") ;; => 0
(compare "B" "C") ;; => -1
(compare "AA" "ZZ") ;; => -25

            
                (compare true false)
;;=> 1
(compare false true)
;;=> -1
(compare true true)
;;=> 0
(compare false false)
;;=> 0