Skip to content

Instantly share code, notes, and snippets.

@magnars
Created February 8, 2022 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magnars/8b71aaae0feb445643fabdbb9d776825 to your computer and use it in GitHub Desktop.
Save magnars/8b71aaae0feb445643fabdbb9d776825 to your computer and use it in GitHub Desktop.
(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