Possibly I'm going about this wrong. I'm trying to understand how best 
to construct maps from sequences, by applying a function which returns a 
key / value pair.

Something like this:

(ns test (:use clojure.contrib.str-utils))

(def test-str "foo=1;bar=2;baz=3")

(defn split-kv [text]
 (let [[k v] (re-split #"=" text )]
   {k v}))

(defn split-pairs [text]
 (re-split #";" text))

(map split-kv (split-pairs test-str))

-> ({"foo" "1"} {"bar" "2"} {"baz" "3"})


Doesn't really do what I had in mind. And yeah, I figured out that I can 
convert that to a hash-map in various ways, but I had expected map to be 
able to do this. So I wrote this:


(defn map-assoc
 "Returns a map consisting of f applied to coll, where f is a function 
returning a key and value. f can return either a sequence with two 
values or a single item map."
 [f coll]
 (loop [map {}
    s (seq coll)]
   (if s
     (let [item (f (first s))]
   (recur (if (associative? item)
        (conj map item)
        (assoc map (first item) (second item)))
          (next s)))
     map)))


This seems a little bit more like what I expected:

(map-assoc split-kv (split-pairs test-str))

-> {"baz" "3", "bar" "2", "foo" "1"}


Am I overlooking some already existing function hidden away someplace 
that does this?

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

Reply via email to