Created
October 10, 2010 23:56
-
-
Save amalloy/619722 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.