On Nov 30, 2008, at 12:14 PM, Randall R Schulz wrote:

>
> On Sunday 30 November 2008 09:06, Randall R Schulz wrote:
>> Hi,
>>
>> 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 ...).
>>
>> Can I get some hints? Do I need to be more specific about where the
>> pairs I'll be adding come from? Is it sufficient to say that the
>> input is a sequence, each element of which will yield another pair to
>> add to the complete map I want to return?
>
> Ha! I think I got it. (I've got something that works, anyway):
>
> (ns rrs.ns-ctags
> (:use clojure.contrib.ns-utils))
>
> (defn ns-var-metas
> "Acquire a map from Var names to their respective metadata
>  maps for each public Var in the specified namespace"
> [ns-name]
> (let [namespace (find-ns ns-name)]
>  (loop [ns-vars (ns-vars namespace)
>         var-map {}]
>   (let [ns-var (first ns-vars)]
>    (if (seq ns-vars)
>     (recur (rest ns-vars)
>            (assoc var-map ns-var (meta (ns-resolve ns-name ns-var))))
>     var-map))))
>
>
>
> Critiques welcome.
>

I like reduce for these things. It will let you perform a  
transformation and assoc conditionally if needed:

(defn ns-var-metas
   "Acquire a map from Var names to their respective metadata
    maps for each public Var in the specified namespace"
   [ns]
   (reduce (fn [ret [name var]]
               (assoc ret name ^var))
           {} (ns-publics (the-ns ns))))

Note that the seq of a map returns map entries that can be  
destructured with [key val], or accessed with (key e), (val e).

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

Reply via email to