Skip to content

Instantly share code, notes, and snippets.

@oshyshko
Last active August 17, 2016 02:41
Show Gist options
  • Save oshyshko/483f3bd3e6fff02d86c2439d9f4b9b82 to your computer and use it in GitHub Desktop.
Save oshyshko/483f3bd3e6fff02d86c2439d9f4b9b82 to your computer and use it in GitHub Desktop.
(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