1.3.0 permalink Arrow_down_16x16

distinct

clojure.core

  • (distinct coll)
Returns a lazy sequence of the elements of coll with duplicates removed

2 Examples top

  • user=> (distinct [1 2 1 3 1 4 1 5])
    (1 2 3 4 5)
  • user=> (def fractions 
             (for [n (range 1 100) d (range (inc n) 100)] 
               (let [gcd (clojure.contrib.math/gcd n d)] 
                 (/ (/ n gcd) (/ d gcd)))))
    ;; all irreducible fractions with denominator < 100
    ;; (1/2 1/3 ... 1/99 2/3 1/2 2/5 1/3 ...)
    
    user=> (count fractions)
    4851
    
    user=> (count (distinct fractions))
    3003
    
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:4413 top

(defn distinct
  "Returns a lazy sequence of the elements of coll with duplicates removed"
  {:added "1.0"
   :static true}
  [coll]
    (let [step (fn step [xs seen]
                   (lazy-seq
                    ((fn [[f :as xs] seen]
                      (when-let [s (seq xs)]
                        (if (contains? seen f) 
                          (recur (rest s) seen)
                          (cons f (step (rest s) (conj seen f))))))
                     xs seen)))]
      (step coll #{})))
Vars in clojure.core/distinct:
Used in 0 other vars

Comments top

1 comment(s) for distinct.

Use this function if you want to remove only consequtive duplicates

(defn distinct-consequtive [sequence] (map first (partition-by identity sequence)))

(distinct-consequtive [1 1 2 3 3 2 2 3])
;=> (1 2 3 2 3)
Log in to add a comment.