On Aug 9, 9:27 am, Chad Harrington <chad.harring...@gmail.com> wrote: > Hi all, > I am learning Clojure and would like to see if there is a better/more > concise/faster/more idiomatic/etc. way to create the age-index below. My > version seems awfully roundabout. The basic concept is a toy database table > stored as a hashmap. Each row has a row-id and and a vector of data [name, > age]. I then create an index on the age column. The index should yield a > row-id for the given age value. My code below works as designed, but I'd > like to see how the age-index could be improved. > > Thanks for your insights. > > Chad > ------------ code begin ---------------- > (use '[clojure.contrib.seq-utils :only (flatten)]) > > (def data { > 0 ["Fred" 30], > 1 ["Wilma" 26], > 2 ["Bam-bam" 2], > 3 ["Dino" 3]}) > > (def age-index > (apply sorted-map > (flatten (map #(list > (nth (val %) 1) > (key %)) > data))))
The intent of the mapping can be made clearer with destructuring I think. Also, flatten is not needed: a core function called "into" will transform a sequence of key/value pairs into a map. (def age-index (into (sorted-map) (map (fn [[k [name age]]] [age k]) data))) > (defn name-by-age [age] > (first (data (age-index age)))) > > (println (name-by-age 26)) > ------------------ code end ------------------- > > Chad Harrington > chad.harring...@gmail.com --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---