Created
June 9, 2010 22:22
-
-
Save michalmarczyk/432276 to your computer and use it in GitHub Desktop.
comparator composition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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