annotate src/clojure/contrib/greatest_least.clj @ 10:ef7dbbd6452c

added clojure source goodness
author Robert McIntyre <rlm@mit.edu>
date Sat, 21 Aug 2010 06:25:44 -0400
parents
children
rev   line source
rlm@10 1 (ns
rlm@10 2 ^{:author "Vincent Foley",
rlm@10 3 :doc "Various functions for finding greatest and least values in a collection"}
rlm@10 4 clojure.contrib.greatest-least)
rlm@10 5
rlm@10 6 (defn- boundary
rlm@10 7 [cmp-fn f & args]
rlm@10 8 (when args
rlm@10 9 (reduce (fn [a b] (if (cmp-fn (compare (f b) (f a)))
rlm@10 10 b
rlm@10 11 a)) args)))
rlm@10 12
rlm@10 13 (defn greatest-by
rlm@10 14 "Return the argument for which f yields the greatest value."
rlm@10 15 [f & args]
rlm@10 16 (apply boundary pos? f args))
rlm@10 17
rlm@10 18 (defn greatest
rlm@10 19 "Return the greatest argument."
rlm@10 20 [& args]
rlm@10 21 (apply greatest-by identity args))
rlm@10 22
rlm@10 23 (defn least-by
rlm@10 24 "Return the argument for which f yields the smallest value."
rlm@10 25 [f & args]
rlm@10 26 (apply boundary neg? f args))
rlm@10 27
rlm@10 28 (defn least
rlm@10 29 "Return the smallest element."
rlm@10 30 [& args]
rlm@10 31 (apply least-by identity args))
rlm@10 32
rlm@10 33
rlm@10 34 (defn- boundary-all
rlm@10 35 [cmp-fn f & args]
rlm@10 36 (when args
rlm@10 37 (reduce (fn [a b]
rlm@10 38 (if (nil? a)
rlm@10 39 (cons b nil)
rlm@10 40 (let [x (compare (f b) (f (first a)))]
rlm@10 41 (cond (zero? x) (cons b a)
rlm@10 42 (cmp-fn x) (cons b nil)
rlm@10 43 :else a))))
rlm@10 44 nil
rlm@10 45 args)))
rlm@10 46
rlm@10 47 (defn all-greatest-by
rlm@10 48 "Return all the elements for which f yields the greatest value."
rlm@10 49 [f & args]
rlm@10 50 (apply boundary-all pos? f args))
rlm@10 51
rlm@10 52 (defn all-greatest
rlm@10 53 "Returns all the greatest elements."
rlm@10 54 [& args]
rlm@10 55 (apply all-greatest-by identity args))
rlm@10 56
rlm@10 57 (defn all-least-by
rlm@10 58 "Return all the elements for which f yields the least value."
rlm@10 59 [f & args]
rlm@10 60 (apply boundary-all neg? f args))
rlm@10 61
rlm@10 62 (defn all-least
rlm@10 63 "Returns all the least elements."
rlm@10 64 [& args]
rlm@10 65 (apply all-least-by identity args))