Created
September 28, 2018 14:33
-
-
Save souenzzo/2a2e74d56fc7bd6e7a35977bfb0939b9 to your computer and use it in GitHub Desktop.
distinct-by
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
(defn distinct-by | |
"Like clojure.core/distinct, but applys f" | |
([f] | |
(fn [rf] | |
(let [seen (volatile! #{})] | |
(fn | |
([] (rf)) | |
([result] (rf result)) | |
([result input] | |
(let [id (f input)] | |
(if (contains? @seen id) | |
result | |
(do (vswap! seen conj id) | |
(rf result input))))))))) | |
([op coll] | |
(let [step (fn step [xs seen] | |
(lazy-seq | |
((fn [[f :as xs] seen] | |
(when-let [s (seq xs)] | |
(let [v (op f)] | |
(if (contains? seen v) | |
(recur (rest s) seen) | |
(cons f (step (rest s) (conj seen v))))))) | |
xs seen)))] | |
(step coll #{})))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment