view 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 source
1 (ns
2 ^{:author "Vincent Foley",
3 :doc "Various functions for finding greatest and least values in a collection"}
4 clojure.contrib.greatest-least)
6 (defn- boundary
7 [cmp-fn f & args]
8 (when args
9 (reduce (fn [a b] (if (cmp-fn (compare (f b) (f a)))
10 b
11 a)) args)))
13 (defn greatest-by
14 "Return the argument for which f yields the greatest value."
15 [f & args]
16 (apply boundary pos? f args))
18 (defn greatest
19 "Return the greatest argument."
20 [& args]
21 (apply greatest-by identity args))
23 (defn least-by
24 "Return the argument for which f yields the smallest value."
25 [f & args]
26 (apply boundary neg? f args))
28 (defn least
29 "Return the smallest element."
30 [& args]
31 (apply least-by identity args))
34 (defn- boundary-all
35 [cmp-fn f & args]
36 (when args
37 (reduce (fn [a b]
38 (if (nil? a)
39 (cons b nil)
40 (let [x (compare (f b) (f (first a)))]
41 (cond (zero? x) (cons b a)
42 (cmp-fn x) (cons b nil)
43 :else a))))
44 nil
45 args)))
47 (defn all-greatest-by
48 "Return all the elements for which f yields the greatest value."
49 [f & args]
50 (apply boundary-all pos? f args))
52 (defn all-greatest
53 "Returns all the greatest elements."
54 [& args]
55 (apply all-greatest-by identity args))
57 (defn all-least-by
58 "Return all the elements for which f yields the least value."
59 [f & args]
60 (apply boundary-all neg? f args))
62 (defn all-least
63 "Returns all the least elements."
64 [& args]
65 (apply all-least-by identity args))