-
-
Save magnars/8b71aaae0feb445643fabdbb9d776825 to your computer and use it in GitHub Desktop.
This file contains 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
(defn max-key* | |
"Returns the x for which (k x) is greatest. | |
Differs from `max-key` in that it uses `compare` instead of `>`." | |
{:static true} | |
([k x] x) | |
([k x y] (if (pos? (compare (k x) (k y))) x y)) | |
([k x y & more] | |
(reduce #(max-key* k %1 %2) (max-key* k x y) more))) | |
(defn min-key* | |
"Returns the x for which (k x) is least. | |
Differs from `min-key` in that it uses `compare` instead of `<`." | |
{:static true} | |
([k x] x) | |
([k x y] (if (neg? (compare (k x) (k y))) x y)) | |
([k x y & more] | |
(reduce #(min-key* k %1 %2) (min-key* k x y) more))) | |
(defn max-by [k coll & [default]] | |
(if (seq coll) | |
(apply max-key* k coll) | |
default)) | |
(defn min-by [k coll & [default]] | |
(if (seq coll) | |
(apply min-key* k coll) | |
default)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment