Created
May 8, 2012 15:37
-
-
Save ghadishayban/2636413 to your computer and use it in GitHub Desktop.
Lazily distinct list
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 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