My version of distinct-by just took clojure.core/distinct and added a keyfn
(and optional max-n). It's hard to claim this code is readable. I took this
approach mostly because I knew it would be unlikely to be buggy, since it
was a simple change or two from clojure.core/distinct
(defn distinct-by
"Like distinct, but calls keyfn to determine distinctness, much like
sort-by.
Takes an optional max-n, indicating how many duplicates are acceptible."
([keyfn coll]
(distinct-by keyfn 1 coll))
([keyfn max-n coll]
(let [step (fn step [xs seen]
(lazy-seq
((fn [[f :as xs] seen]
(when-let [s (seq xs)]
(if (>= (get seen (keyfn f) 0) max-n)
(recur (rest s) seen)
(cons f (step (rest s) (update-in seen [(keyfn
f)] (fnil inc 0)))))))
xs seen)))]
(step coll {}))))
On Sun, Jul 23, 2017 at 8:25 PM, Rob Nikander <[email protected]>
wrote:
> Yes, I find that much clearer too. Thanks!
>
> On Saturday, July 22, 2017 at 4:50:23 PM UTC-4, tbc++ wrote:
>>
>> If we think about what we're doing here is a stateful filter, then maybe
>> we could leverage a few more core Clojure functions:
>>
>>
>> (defn distinct-by [f coll]
>> (let [seen (atom #{})]
>> (filter (fn [itm]
>> (let [m (f itm)]
>> (when-not (@seen m)
>> (swap! seen conj m))))
>> coll)))
>>
>> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to [email protected]
> Note that posts from new members are moderated - please be patient with
> your first post.
> To unsubscribe from this group, send email to
> [email protected]
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en
> ---
> You received this message because you are subscribed to the Google Groups
> "Clojure" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
>
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.