Clojure China

[4Clojure] find distinct items

clojure
#1
(defn find-distinct-items [coll]
  (reduce (fn [xs x]
            (if ((set xs) x) xs
                (conj xs x))) [] coll))

(find-distinct-items '([2 4] [1 2] [1 3] [1 3])) ;;; => [[2 4] [1 2] [1 3]]

以上是一种我认为不太简洁的写法,我本意是想将coll直接转换成set,但是(set coll)这种方式导致无序,不知道sorted-set-by能不能搞定?

#2

clojure.core/distinct 直接支持

#3

可以使用some函数来判断,可以这么写:

(fn [coll] 
  (reduce (fn [coll, target] 
    (if (some #(= target %) coll) 
      coll 
      (conj coll target)
    )) [] coll))