Skip to content

Instantly share code, notes, and snippets.

@amalloy
Created October 10, 2010 23:56
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 amalloy/619722 to your computer and use it in GitHub Desktop.
Save amalloy/619722 to your computer and use it in GitHub Desktop.
user> (defn fast-max [k x & more]
(first
(reduce (fn [[x x-key :as orig] y]
(let [[_ y-key :as new] [y (k y)]]
(if (> x-key y-key)
orig
new)))
[x (k x)]
more)))
#'user/fast-max
user> (time (apply fast-max #(do (Thread/sleep 100) %) (range 100)))
"Elapsed time: 10007.125451 msecs"
99
user> (time (apply max-key #(do (Thread/sleep 100) %) (range 100)))
"Elapsed time: 19811.947463 msecs"
99
@amalloy
Copy link
Author

amalloy commented Oct 10, 2010

Any interest in adding something like this to contrib? It shouldn't replace max-key, since the extra bookkeeping slows things down if k is cheap to apply, but for expensive keys this is better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment