Created
March 10, 2021 15:24
-
-
Save thenonameguy/714b4a4aa5dacc204af60ca0cb15db43 to your computer and use it in GitHub Desktop.
distinct-by clojure transducer
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 | |
"Returns a stateful transducer that removes elements by calling f on each step as a uniqueness key. | |
Returns a lazy sequence when provided with a collection." | |
([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 xs] | |
(sequence (distinct-by f) xs))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment