Last active
August 17, 2016 02:41
-
-
Save oshyshko/483f3bd3e6fff02d86c2439d9f4b9b82 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
(ns whatever) | |
; loop + recur | |
(defn max-comparing | |
([f xs] | |
(when-let [[x & more] (seq xs)] | |
(loop [v x, k (f x), xs more] | |
(if-let [[x & xs] xs] | |
(let [k' (f x)] | |
(if (pos? (compare k k')) | |
(recur v k xs) | |
(recur x k' xs))) | |
v))))) | |
; map + reduce | |
(defn max-comparing-2 [f col] | |
(when-let [xs (map #(vector (f %) %) col)] | |
(second (reduce #(if (pos? (compare (first %1) (first %2))) %1 %2) | |
(first xs) | |
(rest xs))))) | |
; transducer | |
(defn max-comparing-3 [f xs] | |
(if (seq xs) | |
(second (reduce ((map #(vector (f %) %)) | |
#(if (pos? (compare (first %1) (first %2))) %1 %2)) | |
[(f (first xs)) (first xs)] | |
(rest xs))))) | |
(let [f #(do (Thread/sleep 1) (- %)) | |
n 100 | |
xs (repeatedly n #(rand-int Integer/MAX_VALUE)) | |
_ (count xs) | |
samples 10] | |
(assert (= (max-comparing f xs) | |
(max-comparing-2 f xs) | |
(max-comparing-3 f xs))) | |
(time (doseq [_ (range samples)] (max-comparing f xs))) | |
(time (doseq [_ (range samples)] (max-comparing-2 f xs))) | |
(time (doseq [_ (range samples)] (max-comparing-3 f xs)))) | |
; => nil | |
; "Elapsed time: 1358.381828 msecs" | |
; "Elapsed time: 1347.90348 msecs" | |
; "Elapsed time: 1357.485049 msecs" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment