Skip to content

Instantly share code, notes, and snippets.

@jackrr
Created February 5, 2022 20:34
Show Gist options
  • Select an option

  • Save jackrr/b70ae84efffe052276c16266ac3f7eec to your computer and use it in GitHub Desktop.

Select an option

Save jackrr/b70ae84efffe052276c16266ac3f7eec to your computer and use it in GitHub Desktop.
Lazily remove duplicate members of list, by predicate "hashing" function on members
(defn distinct-p
([pred coll]
(distinct-p pred coll #{}))
([pred coll seen]
(if (empty? coll)
'()
(lazy-seq
(let [next (first coll)
key (pred next)
is-dup (contains? seen key)
recurred (distinct-p pred (rest coll) (if is-dup seen (conj seen key)))]
(if is-dup
recurred
(cons next recurred)))))))
@jackrr
Copy link
Copy Markdown
Author

jackrr commented Feb 5, 2022

Example:

(distinct-p :id [{:id 1 :v "one"} {:id 2 :v "two"} {:id 1 :v "another 1"}])
;; -> ({:id 1, :v "one"} {:id 2, :v "two"})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment