Created
October 31, 2018 17:54
-
-
Save csm/3d45ea4602b7a8d193e6fc73da939e21 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
(defn distinct-by | |
"Like distinct, but uses f to consider what duplicate values are." | |
([f] | |
(fn [rf] | |
(let [seen (volatile! #{})] | |
(fn | |
([] (rf)) | |
([result] (rf result)) | |
([result input] | |
(let [v (f input)] | |
(if (contains? @seen v) | |
result | |
(do (vswap! seen conj v) | |
(rf result input))))))))) | |
([f coll] | |
(let [step (fn step [xs seen] | |
(lazy-seq | |
((fn [[item :as xs] seen] | |
(when-let [s (seq xs)] | |
(let [v (f item)] | |
(if (contains? seen v) | |
(recur (rest s) seen) | |
(cons item (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