Thanks Christophe,
> Using a default return value, you can rewrite the (if-let...) as (conj
> (amap key ()) item).
A good point, getting clojure and clojure :)
(defn seq-to-multimap
"takes a sequence s of possibly repeating elements
and converts it to a map, where keys are obtained
by applying key-fn to elements of s and values are
sequences of all elements of s with a given key"
[s key-fn]
(reduce
(fn [m el]
(let [key (key-fn el)]
(assoc m key (conj (m key []) el))))
{} s))
Boris
On Apr 28, 5:31 pm, Christophe Grand <[email protected]> wrote:
> Hi Boris,
>
> Boris Mizhen a écrit :
>
>
>
> > I am starting to learn clojure. I would appreciate comments on the
> > utility function below.
> > Coding style, idiomatic Clojure, comment style, efficiency, naming
> > conventions, indentations (used slime) ... anything I should
> > improve :)
>
> > (defn seq-to-multimap [s key-fn]
> > "takes a sequence s of possibly repeating elements
> > and converts it to a map, where keys are obtained by applying key-
> > fn
> > to elements of s and values are sequence of all elements of s with
> > the
> > particular key"
> > (reduce
> > (fn [amap item]
> > (let [key (key-fn item)]
> > (assoc amap key
> > (if-let [it (amap key)]
> > (conj it item)
> > (list item)))))
> > {} s))
>
> First, you misplaced the docstring: it comes before the args vector.
> Using a default return value, you can rewrite the (if-let...) as (conj
> (amap key ()) item).
>
> > user> (seq-to-multimap [1 :key :key 2 3 3 nil] #(identity %1))
> > {nil (nil), 3 (3 3), 2 (2), :key (:key :key), 1 (1)}
>
> Here you don't need to write #(identity %1), "identity" suffices.
>
> > Would it be better to have this function to create a list of lists
> > using an equality op instead?
>
> I think it's a better choice to have it return a map because, to compute
> the result, you need to efficiently index by key.
>
> --
> Professional:http://cgrand.net/(fr)
> On Clojure:http://clj-me.blogspot.com/(en)
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To post to this group, send email to [email protected]
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
-~----------~----~----~----~------~----~------~--~---