And this is mine
(defn keycollect-too [key-fn coll]
(let [not-key (complement key-fn)]
(loop [[k & more] coll, res (transient {})]
(let [[vv rr] (split-with not-key more)]
(if-not k
(persistent! res)
(recur rr (assoc! res k (vec vv))))))))
(keycollect-too keyword? [:key1 1 2 3 :key2 4 :key3 5 6 7]) => {:key1 [1 2
3], :key2 [4], :key3 [5 6 7]}
Thanks.
On Wednesday, February 20, 2013 6:50:42 AM UTC-5, Stefan Kamphausen wrote:
>
> Hi,
>
> given a vector of the form
>
>
>
> [:key1 1 2 3 :key2 4 :key3 5 6 7]
>
> I wand to create a map collecting the items behind each keyword as a vector
> like this:
>
> {:key1 [1 2 3]
> :key2 [4]
> :key3 [5 6 7]}
>
> I have already written two functions which achieve this, but neither of them
> "feels good" and I am interested in more elegant and idiomatic solutions.
>
> (defn keycollect-partition [coll]
> (->> coll
> (partition-by keyword?) ; bundle at key
> (partition 2) ; kw + its arg
> (map (fn [[[sec] arg]] [sec (vec arg)])) ; destruct the mess
> (into {}))) ; make it a map
>
> (defn keycollect-reduce [coll]
> (apply zipmap
> (reduce
> (fn [ac x]
> (if (keyword? x)
> [(conj (first ac) x) (conj (second ac) [])]
> (update-in ac [1 (dec (count (first ac)))] conj x))) [[] []]
> coll)))
>
> Added complexity: My original vector does not yet contain keywords, but I
> construct them in a map regexp-matching each item and creating a keyword from
> the first group of the match.
>
> Any pointers or ideas appreciated.
>
> Regards,
> Stefan
>
>
>
>
--
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
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
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.