Skip to content

Instantly share code, notes, and snippets.

@souenzzo
Created September 28, 2018 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save souenzzo/2a2e74d56fc7bd6e7a35977bfb0939b9 to your computer and use it in GitHub Desktop.
Save souenzzo/2a2e74d56fc7bd6e7a35977bfb0939b9 to your computer and use it in GitHub Desktop.
distinct-by
(defn distinct-by
"Like clojure.core/distinct, but applys f"
([f]
(fn [rf]
(let [seen (volatile! #{})]
(fn
([] (rf))
([result] (rf result))
([result input]
(let [id (f input)]
(if (contains? @seen id)
result
(do (vswap! seen conj id)
(rf result input)))))))))
([op coll]
(let [step (fn step [xs seen]
(lazy-seq
((fn [[f :as xs] seen]
(when-let [s (seq xs)]
(let [v (op f)]
(if (contains? seen v)
(recur (rest s) seen)
(cons f (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