Hi Conrad,
I find this an interesting question because there is already a select
function in clojure.set, but it only works on sets. Why shouldn't it
work on maps? To make select work with maps we just replace disj with
dissoc:
(defn select
"Returns a set of the elements for which pred is true"
[pred xset]
(reduce (fn [s k] (if (pred k) s (dissoc s (key k))))
xset xset))
(def m {:dog 5 :cat 4 :mouse 7 :cow 6})
(select (comp even? val) m)
{:cat 4, :cow 6}
If select was to support maps there seem to be a number of options:
1) allow disj to work on maps as (dissoc s (key %))
2) test if xset is a hashmap and use a different reduce function
3) have separate functions (or namespaces)
4) have a multi-method
Regards,
Tim.
On Sep 2, 9:35 am, Conrad <[email protected]> wrote:
> Hi everyone! I was wondering if there was a better idiom in Clojure
> for filtering items from a map... Suppose we want to remove all items
> from a map that have an odd number as a value. Here's how I'd write
> it:
>
> => (apply hash-map
> (apply concat
> (filter (fn [[key val]]
> (even? val))
> {:dog 5 :cat 4 :mouse 7 :cow 6})))
>
> {:cow 6, :cat 4}
>
> This is ugly. Is there a more elegant way to write this kind of code?
> Please share!
>
> Thanks!
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---