Skip to content

Instantly share code, notes, and snippets.

@michalmarczyk
Created June 9, 2010 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michalmarczyk/432276 to your computer and use it in GitHub Desktop.
Save michalmarczyk/432276 to your computer and use it in GitHub Desktop.
comparator composition
user> (defn multi-comparator [& comps]
(reify java.util.Comparator
(compare [this x y]
(reduce (fn [r ^java.util.Comparator c]
(if (zero? r) (.compare c x y) r))
0
comps))))
#'user/multi-comparator
;;; earlier versions, last-to-first
user> (defn multi-comparator [& comps]
(reify java.util.Comparator
(compare [this x y]
(reduce (fn [r c]
(if (zero? r) (c x y) r))
0
comps))))
#'user/multi-comparator
user> (def test-set (sorted-set-by (multi-comparator (fn [x y] (compare (count x) (count y))) compare)))
#'user/test-set
user> ((into test-set [[1 2 3] [4 5 6] [7 8 9] [10 11 12] [13 14 15]]) [7 8 9])
[7 8 9]
user> (defn multi-comparator [& comps]
(reify java.util.Comparator
(compare [this x y]
(loop [comps comps r 0]
(if-let [c (and (zero? r) (first comps))]
(recur (next comps) (c x y))
r)))))
#'user/multi-comparator
user> (def test-set (sorted-set-by (multi-comparator (fn [x y] (compare (count x) (count y))) compare)))
#'user/test-set
user> ((into test-set [[1 2 3] [4 5 6] [7 8 9] [10 11 12] [13 14 15]]) [7 8 9])
[7 8 9]
user> (defn comparator* [& comps]
(fn [x y]
(reduce (fn [r c] (if (zero? r) (c x y) r))
0
comps)))
#'user/comparator*
user> (def test-set (sorted-set-by (comparator* (fn [x y] (compare (count x) (count y))) compare)))
#'user/test-set
user> ((into test-set [[1 2 3] [4 5 6] [7 8 9] [10 11 12] [13 14 15]]) [7 8 9])
[7 8 9]
user> (defn comparator** [& preds]
(fn [x y]
(reduce (fn [r p] (if (zero? r) (cond (p x y) -1 (p y x) 1 :else 0) r))
0
preds)))
#'user/comparator**
user> (def test-set2 (sorted-set-by (comparator** (fn [x y] (< (count x) (count y))) (fn [x y] (some true? (map < x y))))))
#'user/test-set2
user> ((into test-set2 [[1 2 3] [4 5 6] [7 8 9] [10 11 12] [13 14 15]]) [7 8 9])
[7 8 9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment