Skip to content

Instantly share code, notes, and snippets.

@bnyeggen
Created August 31, 2012 13:17
Show Gist options
  • Save bnyeggen/3552552 to your computer and use it in GitHub Desktop.
Save bnyeggen/3552552 to your computer and use it in GitHub Desktop.
Three ways of distinctifying a sequence and returning a vec
(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