You're viewing version 1.2.0 of comparator. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16

comparator

clojure.core

  • (comparator pred)
Returns an implementation of java.util.Comparator based upon pred.

1 Example top

  • ;; simple example to create an ArrayList, initially [1,2,0]
    ;; and sort it in descending order
    
    user=> (def a (new java.util.ArrayList [1 2 0]))
    #'user/a
    user=> (def compx (comparator (fn [x y] (> x y))))
    #'user/compx
    user=> (java.util.Collections/sort a compx)
    nil
    user=> a
    #<ArrayList [2, 1, 0]>
    
    ;; Note however that 'comparator' is rarely (never?) needed because if
    ;; the fn returns a boolean, the .compare implementation Clojure provides
    ;; causes it to behave the same as if 'comparator' were wrapped around it:
    
    (sort (comparator (fn [x y] (> x y))) [1 2 0]) ;=> (2 1 0)
    (sort (fn [x y] (> x y)) [1 2 0])              ;=> (2 1 0)
    (sort > [1 2 0])                               ;=> (2 1 0)
    (sort < [1 2 0])                               ;=> (0 1 2)
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:2322 top

(defn comparator
  "Returns an implementation of java.util.Comparator based upon pred."
  {:added "1.0"}
  [pred]
    (fn [x y]
      (cond (pred x y) -1 (pred y x) 1 :else 0)))
Vars in clojure.core/comparator: cond defn fn
Used in 2 other vars sorted-map-by sorted-set-by

Comments top

No comments for comparator. Log in to add a comment.