Hi,

Am 07.02.2011 um 18:20 schrieb Justin Kramer:

> Checking out clojure.core/destructure and clojure.core/let might be
> helpful.
> 
> Here's a macro I hacked together. It doesn't work with :keys, :as,
> or :or. I take no responsibility if you use it for anything real. But
> maybe it will provide you with some ideas.
> 
> (defmacro destructure->map
>  [bvec val]
>  `(let [~bvec ~val]
>     (-> {}
>         ~@(for [s (remove #(= '& %) (flatten bvec))]
>             `(assoc (-> (quote ~s) name keyword) ~s)))))
> 
> Example:
> 
> (let [v [1 2 [3 4 5 6 7 8]]]
>  (destructure->map [a b [c d & e]] v))
> => {:e (5 6 7 8), :d 4, :c 3, :b 2, :a 1}

Straight-forward, ugly loop solution:

(defn destruct
  [pattern coll]
  (loop [ps (seq pattern)
         s  (seq coll)
         ls {}]
    (let [local (first ps)]
      (cond
        ; patterns exhausted? done
        (nil? ps)
        ls

        ; "local" is a seq? => descent
        (seq? local)
        (recur (next ps) (next s) (merge ls (destruct local (first s))))

        ; "local" is something & like? => bind the rest and done.
        (= "&" (name local))
        (assoc ls (second ps) s)

        ; default => bind the local in the map.
        :else
        (recur (next ps) (next s) (assoc ls local (first s)))))))

user=> (destruct '(a b (c d & e)) [1 2 [3 4 5 6 7 8]])
{c 3, d 4, e (5 6 7 8), b 2, a 1}

Sincerely
Meikel

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

Reply via email to