Skip to content

Instantly share code, notes, and snippets.

@akovantsev
Created July 24, 2021 09:48
Show Gist options
  • Save akovantsev/6ab7283cad344ca0a6d77b1116de60c9 to your computer and use it in GitHub Desktop.
Save akovantsev/6ab7283cad344ca0a6d77b1116de60c9 to your computer and use it in GitHub Desktop.
(defn distinct-by
([f]
(fn [rf]
(let [seen (volatile! #{})]
(fn
([] (rf))
([result] (rf result))
([result x]
(let [v (f x)]
(if (contains? @seen v)
result
(do (vswap! seen conj v)
(rf result x)))))))))
([f coll]
(let [step (fn step [xs seen]
(lazy-seq
((fn [[x :as xs] seen]
(when-let [s (seq xs)]
(let [v (f x)]
(if (contains? seen v)
(recur (rest s) seen)
(cons x (step (rest s) (conj seen v)))))))
xs seen)))]
(step coll #{}))))
(->> [[1 1] [2 1] [1 2] [2 2] [1 3] [2 3]]
(distinct-by first))
;=> ([1 1] [2 1])
(->> [[1 1] [2 1] [1 2] [2 2] [1 3] [2 3]]
(into []
(comp
(filter #(-> % second odd?))
(distinct-by first))))
;=> [[1 1] [2 1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment