Skip to content

Instantly share code, notes, and snippets.

@francoisdevlin
Created July 10, 2009 15:29
Show Gist options
  • Save francoisdevlin/144590 to your computer and use it in GitHub Desktop.
Save francoisdevlin/144590 to your computer and use it in GitHub Desktop.
(defn chain-comp
"This takes a list of comparator functions, and chains them together.
It returns another comparator. It behaves similar to comp, in that
comparisons are done right to left."
[& comps]
(fn [a b]
(loop [remaining-comps (reverse comps)]
(let [iter-comp (first remaining-comps)
iter-result (iter-comp a b)]
(if (and (zero? iter-result) (next remaining-comps))
(recur (rest remaining-comps))
iter-result)))))
(defn <=>
"This creates a comparator that wraps the mapping fn f."
[f]
(fn [a b]
(compare (f a) (f b))))
(defn inv-<=>
"This creates an inverse comparator that wraps the mapping fn f."
[f]
(fn [a b]
(compare (f b) (f a))))
(defn inv-compare
"This function takes a comparator f (with two inputs) as an input, and reverses it."
[f]
(fn [a b](f b a)))
(defn least
([comp-fn coll] (first (sort comp-fn coll))))
(defn most
([comp-fn coll] (first (sort (inv-compare comp-fn) coll))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment