I frequently use a more general version of this function that reduces
a seq to a map, mapping each element in the seq to a [key value] pair
for the map. I use this in several different libs:
(defn mash
"Reduce a seq-able to a map. The given fn should return a 2-element tuple
representing a key and value in the new map."
[f coll]
(reduce
(fn [memo elem]
(let [[k v] (f elem)]
(assoc memo k v)))
{} coll))
Where "mash" comes from map + hash.
(mash (fn [elem] [(+ 1 elem) (+ 2 elem)]) (list 1 2 3))
=> {4 5, 3 4, 2 3}
You could also use into:
(into {} (map (fn [elem] [(+ 1 elem) (+ 2 elem)]) (list 1 2 3)))
=> {4 5, 3 4, 2 3}
- Mark
On Thu, Feb 5, 2009 at 7:33 AM, Rich Hickey <[email protected]> wrote:
>
>
>
> On Feb 4, 10:36 pm, Conrad <[email protected]> wrote:
>> It is useful to build a map from a list of keys and a value generator
>> function. Of Course, such a function is easy to write:
>>
>> (defn genmap [keys fun]
>> (zipmap keys (map fun keys)))
>>
>> In fact, it seems so useful that it must be in the standard API
>> somewhere, but I can't find it... did I miss it somewhere, or was I
>> right to create my own? Please let me know if I'm reinventing the
>> wheel.
>>
>>
>
> It does seem useful, although the zipmap call is already concise.
>
> I wonder if this is a frequently reinvented wheel.
>
> Rich
>
> >
>
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---