Skip to content

Instantly share code, notes, and snippets.

@ghadishayban
Created May 8, 2012 15:37
Show Gist options
  • Save ghadishayban/2636413 to your computer and use it in GitHub Desktop.
Save ghadishayban/2636413 to your computer and use it in GitHub Desktop.
Lazily distinct list
(defn lazily-distinct [coll]
"Returns a lazy distinct list of possibly infinite collection.
Does not realize the whole collection."
(letfn [(lazystep [seen l]
(lazy-seq
(when (seq l)
(loop [next-item (first l) lazy-list (rest l)]
(if (get seen next-item)
(recur (first lazy-list) (rest lazy-list))
(cons next-item (lazystep (conj seen next-item)
lazy-list)))))))]
(lazystep #{} coll)))
;; (count (distinct (take 1000 (repeatedly #(rand-int 5000))))) -> probably less than 1000
;; (count (distinct (take 1000 (lazily-distinct (repeatedly #(rand-int 5000)))))) -> exactly 1000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment