On Sunday 30 November 2008 09:14, Chouser wrote:
> On Sun, Nov 30, 2008 at 12:06 PM, Randall R Schulz <[EMAIL PROTECTED]> 
wrote:
> > This is my first Clojure how-to question. I tried to find an answer
> > on the Wiki and in the list archives, but to no avail.
> >
> > How do I build up a map one association at a time? Clearly (map
> > ...) won't do that, 'cause the output has as many elements as the
> > input. I looked at (reduce ...) but can't see how to make that
> > work. The only piece of the puzzle I can see being involved is
> > (assoc ...).
>
> user=> (def seq-of-pairs (seq [[:a 1] [:b 2] [:c 3]]))
> #'user/seq-of-pairs
> user=> (into {} seq-of-pairs) ; best, most idiomatic
> {:c 3, :b 2, :a 1}
> user=> (apply conj {} seq-of-pairs) ; only if you'd never heard of
> into {:c 3, :b 2, :a 1}
> user=> (reduce conj {} seq-of-pairs) ; perhaps you want to do
> something more than just conj
> {:c 3, :b 2, :a 1}
> user=> (reduce (fn [m [k v]] (assoc m k v)) {} seq-of-pairs) ; if you
> really want to use assoc
> {:c 3, :b 2, :a 1}
>
> --Chouser

Thanks. Those are certainly more concise that what I concocted.

What would they look like if the sequence does not already contain the 
pairs, but rather they must be computed from each element of the 
sequence? Clearly I could build the sequence of pairs separately in 
advance, but that seems wasteful and entails the creation of lots of 
short-lived vectors or lists each holding exactly two elements.

Check out my follow-up to the original posting, if you care to see the 
details of the case at hand.


Randall Schulz

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

Reply via email to