Created
August 31, 2012 13:17
-
-
Save bnyeggen/3552552 to your computer and use it in GitHub Desktop.
Three ways of distinctifying a sequence and returning a vec
This file contains 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 unique-vec1 | |
"Straight-up Clojure sequence traversal" | |
[s] | |
(vec (set s))) | |
(defn unique-vec2 | |
"Conj into transient set and vectorize" | |
[s] | |
(loop [remaining s | |
seen (transient #{})] | |
(if (empty? remaining) (vec (persistent! seen)) | |
(recur (next remaining) (conj! seen (first remaining)))))) | |
(defn unique-vec3 | |
"Use set as distinctifier, but conj into transient vector" | |
[s] | |
(loop [remaining s | |
seen #{} | |
out (transient [])] | |
(if (empty? remaining) (persistent! out) | |
(let [this (first remaining)] | |
(if (contains? seen this) | |
(recur (next remaining) seen out) | |
(recur (next remaining) (conj seen this) (conj! out this))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment