On 08/02/2012 03:05, Asim Jalis wrote:
I frequently find myself passing around maps that are basically structs.
I use this macro to destructure the fields into let variables.

; Macro.

(defmacro def-fields [struct-name & fields]
   (let [field-symbol-vector (->> fields (map name) (map symbol) vec)
         arg (gensym)
         body (gensym)
         macro-name (symbol (str "let-" struct-name))]
     `(defmacro ~macro-name [~arg & ~body]
       `(let [{:keys ~'~field-symbol-vector} ~~arg] ~@~body))))
; How to use it.

(def-fields person :first-name :last-name :city)

(defn print-person [p]
   (let-person p
     (println "First name:" first-name)
     (println "Last name:" last-name)
     (println "City:" city)))

(def person1 {:first-name "John" :last-name "Smith" :city "San Francisco"})
(print-person person1)


I haven't come around macros yet, but when I'll tackle the subject (soon) your example will be useful. Nice! Now I understand a little more the notion of extensible language.

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