Skip to content

Instantly share code, notes, and snippets.

@csm
Created October 31, 2018 17:54
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save csm/3d45ea4602b7a8d193e6fc73da939e21 to your computer and use it in GitHub Desktop.
(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