add value extraction param to distinct

25 views
Skip to first unread message

rod naph

unread,
Jun 13, 2013, 3:36:05 PM6/13/13
to cloju...@googlegroups.com
(Please correct me if there's a better way to do this)

distinct currently only takes one argument, the sequence to filter.  if you're filtering a single level seq that's fine, but if you can't filter any more interesting elements, for example...

[{:id 1 :value "foo"} {:id 2 :value "foo"} {:id 3 :value "bar"}]

i suggest adding a first parameter to extract the value from each element being compared.

(defn distinct
  "Returns a lazy sequence of the elements identified by f of coll with duplicates removed"
  {:added "1.0"
   :static true}
  ([coll] (distinct identity coll))
  ([f coll]
    (let [step (fn step [xs seen]
                   (lazy-seq
                    ((fn [[vs :as xs] seen]
                      (let [v (f vs)]
                        (when-let [s (seq xs)]
                          (if (contains? seen v)
                            (recur (rest s) seen)
                            (cons vs (step (rest s) (conj seen v)))))))
                     xs seen)))]
      (step coll #{}))))

Then allowing to use like...

(->> values
     (distinct :value)
     (map etc...))

Or is there a better way of doing this in core?

Tom Jack

unread,
Jun 13, 2013, 3:46:15 PM6/13/13
to cloju...@googlegroups.com


--
You received this message because you are subscribed to the Google Groups "Clojure Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to clojure-dev...@googlegroups.com.
To post to this group, send email to cloju...@googlegroups.com.
Visit this group at http://groups.google.com/group/clojure-dev.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages