Created
July 24, 2021 09:48
-
-
Save akovantsev/6ab7283cad344ca0a6d77b1116de60c9 to your computer and use it in GitHub Desktop.
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 | |
([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