Hi,

I would like to suggest an enhancement to the  clojure.core/group-by  
function. The idea came from using Enumerable.GroupBy 
<http://msdn.microsoft.com/en-us/library/bb534304.aspx>extension method in 
.NET quite much. It is really handy to have an optional value-mapper 
function which transforms the elements before adding them to the collection 
under the key. It is backward compatible, because calling the overload with 
2 parameters can call the 3 parameter one with clojure.corj/identity as 
value-mapper function.

The implementation is easy-peasy (almost the same as the original):

(defn group-by
  ([f g coll]
     (persistent!
      (reduce
       (fn [ret x]
         (let [k (f x)]
           (assoc! ret k (conj (get ret k []) (g x)))))
       (transient {}) coll)))
  ([f coll]
     (group-by f identity coll)))

Without the value-mapper argument it is very awkward to achieve the same 
structure after the group-by call. Also, doing the transformation before 
the group-by is often impossible, because the key function depends on some 
property of the source element, which would be removed after the 
transformation.

To demonstrate the usage, check out the below calls:

(def animals [{:name "Betsy" :type :cow}
              {:name "Murmur" :type :cat}
              {:name "Lessie" :type :dog}
              {:name "Dingo" :type :dog}
              {:name "Rosie" :type :cat}
              {:name "Rex" :type :dog}
              {:name "Alf" :type :cat}])

(group-by :type animals) ; old usage
> ... ugly stuff

(group-by :type :name animals) ; new usage
> {:cow ["Betsy"], :cat ["Murmur" "Rosie" "Alf"], :dog ["Lessie" "Dingo" 
"Rex"]}

(group-by :type #(.toUpperCase (:name %)) animals) ; hell yeah!
> {:cow ["BETSY"], :cat ["MURMUR" "ROSIE" "ALF"], :dog ["LESSIE" "DINGO" 
"REX"]}

It would be so cool to have this in the core. What do you guys think?

Regards,
Daniel Dinnyes

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to