diff 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
line wrap: on
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/clojure/contrib/greatest_least.clj	Sat Aug 21 06:25:44 2010 -0400
     1.3 @@ -0,0 +1,65 @@
     1.4 +(ns 
     1.5 +  ^{:author "Vincent Foley",
     1.6 +     :doc "Various functions for finding greatest and least values in a collection"}
     1.7 +  clojure.contrib.greatest-least)
     1.8 +
     1.9 +(defn- boundary
    1.10 +  [cmp-fn f & args]
    1.11 +  (when args
    1.12 +    (reduce (fn [a b] (if (cmp-fn (compare (f b) (f a)))
    1.13 +                        b
    1.14 +                        a)) args)))
    1.15 +
    1.16 +(defn greatest-by
    1.17 +  "Return the argument for which f yields the greatest value."
    1.18 +  [f & args]
    1.19 +  (apply boundary pos? f args))
    1.20 +
    1.21 +(defn greatest
    1.22 +  "Return the greatest argument."
    1.23 +  [& args]
    1.24 +  (apply greatest-by identity args))
    1.25 +
    1.26 +(defn least-by
    1.27 +  "Return the argument for which f yields the smallest value."
    1.28 +  [f & args]
    1.29 +  (apply boundary neg? f args))
    1.30 +
    1.31 +(defn least
    1.32 +  "Return the smallest element."
    1.33 +  [& args]
    1.34 +  (apply least-by identity args))
    1.35 +
    1.36 +
    1.37 +(defn- boundary-all
    1.38 +  [cmp-fn f & args]
    1.39 +  (when args
    1.40 +    (reduce (fn [a b]
    1.41 +              (if (nil? a)
    1.42 +                (cons b nil)
    1.43 +                (let [x (compare (f b) (f (first a)))]
    1.44 +                  (cond (zero? x) (cons b a)
    1.45 +                        (cmp-fn x) (cons b nil)
    1.46 +                        :else a))))
    1.47 +            nil
    1.48 +            args)))
    1.49 +
    1.50 +(defn all-greatest-by
    1.51 +  "Return all the elements for which f yields the greatest value."
    1.52 +  [f & args]
    1.53 +  (apply boundary-all pos? f args))
    1.54 +
    1.55 +(defn all-greatest
    1.56 +  "Returns all the greatest elements."
    1.57 +  [& args]
    1.58 +  (apply all-greatest-by identity args))
    1.59 +
    1.60 +(defn all-least-by
    1.61 +  "Return all the elements for which f yields the least value."
    1.62 +  [f & args]
    1.63 +  (apply boundary-all neg? f args))
    1.64 +
    1.65 +(defn all-least
    1.66 +  "Returns all the least elements."
    1.67 +  [& args]
    1.68 +  (apply all-least-by identity args))