Created
October 31, 2018 17:54
Star
You must be signed in to star a gist
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 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