Skip to content

Instantly share code, notes, and snippets.

@thenonameguy
Created March 10, 2021 15:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thenonameguy/714b4a4aa5dacc204af60ca0cb15db43 to your computer and use it in GitHub Desktop.
Save thenonameguy/714b4a4aa5dacc204af60ca0cb15db43 to your computer and use it in GitHub Desktop.
distinct-by clojure transducer
(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