Thanks, that makes a lot of sense!

Per



On May 20, 10:36 am, Chouser <chou...@gmail.com> wrote:
> On Wed, May 20, 2009 at 9:59 AM, Michael Reid <kid.me...@gmail.com> wrote:
>
> > On Wed, May 20, 2009 at 8:44 AM, pmf <phil.fr...@gmx.de> wrote:
>
> >> On May 20, 4:47 am, Per <nondual...@gmail.com> wrote:
> >>> ;; The macro
> >>> (defmacro def-fields [name  tgs]
> >>>   `(defstruct ~name ~@(map #(symbol (str ":" %)) tgs))
> >>> )
>
> >> If you replace the call to 'symbol' with a call to 'keyword', it works
> >> (I think this is what you intended).
>
> > I don't think its that simple. I still get the error if I change it to
> > a call to 'keyword'. The problem I believe is that because def-fields
> > is a macro, the arguments are not evaluated, so in the macro, tgs is
> > bound to the symbol 'tags _not_ the value of tags as defined above the
> > macro.
>
> Yes.  And attempts to resolve or evaluate a macro's args at
> compile time can get squirrelly, will never work with
> locals, etc.
>
> Generally, it's best to see if you can find a non-macro that
> will build what you want, so that you can let the evaluation
> happen at runtime, where it will behave more often as
> expected.  In this case you're in luck, because defstruct (a
> macro) is built on create-struct (a function):
>
> (defmacro def-fields [name tgs]
>   `(def ~name (apply create-struct (map keyword ~tgs))))
>
> user=> (def tags ["name" "age"])
> #'user/tags
> user=> (def-fields fs tags)
> #'user/fs
> user=> (def testfs (struct fs "Peter" "5"))
> #'user/testfs
> user=> testfs
> {:name "Peter", :age "5"}
>
> --Chouser
--~--~---------~--~----~------------~-------~--~----~
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