On Tue, Nov 17, 2009 at 3:59 PM, nchubrich <nicholas.chubr...@gmail.com>wrote:
> How do you def a symbol that you make using (symbol)? I.E. if I try > to do (def (symbol "x") 2) I get: > java.lang.Exception: Second argument to def must be a Symbol. (And > why does it say the \second argument must be a symbol?) > Special forms and macros don't evaluate their arguments. So def's second argument here is a list of the symbol "symbol" and the string literal "x". There are two ways to do what you want: macros and eval. Macro: (defmacro def-from-string [sym-name-string initial-value] `(def ~(symbol sym-name-string) ~initial-value)) will let you use (def-from-string "x" 2) to achieve what you attempted above. (Making the initial binding optional, as in "def", is left as an exercise for the reader. So is providing a way to attach metadata.) Eval: (eval (list 'def (symbol "x") 2)) will intern the symbol in some namespace or another when executed. You might also (eval `(binding [*ns* foo] (def ~(symbol "x") 2))) to have absolute and certain control over exactly what namespace. This has the disadvantage of using the perilous "eval", but the advantage that you can even intern the symbol at run-time; the string "x" can even come from the network or user or otherwise not have been known at compile-time, or the initial root binding 2, or the namespace even. (Similar constructs can be used to create whole namespaces on the fly at runtime. But that's serious metaprogramming.) -- 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