Hi,

The exceptions stems from the call to vec. vec turns a collections
(read: seqable thing) into a vector. The right function calls is
"vector".

(defn my-group-by
  [f coll]
  (let [test (fn [m x]
               (let [res (f x)]
                 (if (key? res m)
                   (conj (m res) x)
                   (assoc m res (vector x)))))]
    (reduce test {} coll)))

Then your conj call, doesn't work. You have to use update-in to update
the vector in case the key is already known.

(defn my-group-by
  [f coll]
  (let [test (fn [m x]
               (let [res (f x)]
                 (if (key? res m)
                   (update-in m [res] conj x)
                   (assoc m res (vector x)))))]
    (reduce test {} coll)))

"key?" is built-in as "contains?".

(defn my-group-by
  [f coll]
  (let [test (fn [m x]
               (let [res (f x)]
                 (if (contains? m res)
                   (update-in m [res] conj x)
                   (assoc m res (vector x)))))]
    (reduce test {} coll)))

You can use fnil to skip the contains? test completely. fnil takes a
function and a value (in the simple case) and replaces the possible
nil as first argument with the given value. So when the map does not
contain the result we will "call" our conj as ((fnil conj []) nil x)
("(conj nil x)"), but fnil will replace the nil with [], so we
actually get (conj [] x). In the next round the result will be
contained and the non-nil value will be passed through to conj. --
Explained quite badly, but I hope you get the idea. Jay Fields also
blogged about fnil recently[1]. You may find his explanation more
clear.

(defn my-group-by
  [f coll]
  (let [test (fn [m x]
               (let [res (f x)]
                 (update-in m [res] (fnil conj []) x)))]
    (reduce test {} coll)))

Hope that helps.

Sincerely
Meikel

[1]: http://blog.jayfields.com/2011/01/clojure-fnil.html

-- 
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