2010/12/15 Emeka <emekami...@gmail.com>

> *Helllo All,*
> *
> *
> *Is there a better way of doing this?*
> *
> *
> *(defmacro foo [string] (let[b# string f# (symbol b#)] `(def ~f#  ~b#)))*
>

Hello,

What is it supposed to be used ?

What do you expect the macroexpansion to look like ?

As is stands, your example can go without the ending #'s since they aren't
declared inside the returned quoted expr. They're useless.

So having

(defmacro foo [string] (let [b string f (symbol string)] `(def ~f ~b)))

But now, string is not (as you may think) evaluated within the let in the
macro. string is just an immutable datastructure containing "as is" what has
been passed to foo. So if what you pass to foo is something which
"evaluates" to a string, for example a string concatenation expression as
(str "the-" "value"), then the code will not do what it suggests it's doing
:

user=> (defmacro foo [string] (let[b# string f# (symbol b#)] `(def ~f#
~b#)))
#'user/foo
user=> (foo (str "the-" "value"))
java.lang.ClassCastException: clojure.lang.PersistentList cannot be cast to
java.lang.String (NO_SOURCE_FILE:0)
user=> (macroexpand '(foo (str "the-" "value")))
java.lang.ClassCastException: clojure.lang.PersistentList cannot be cast to
java.lang.String (NO_SOURCE_FILE:0)
user=>


Now, if you just want the macro to take literal strings as input, then the
code can be further simplified to :

(defmacro foo [string] `(def ~(symbol string) ~string))

user=> (defmacro foo [string] `(def ~(symbol string) ~string))
#'user/foo
user=> (foo "the-string")
#'user/the-string
user=> the-string
"the-string"
user=> (macroexpand '(foo "the-string"))
(def the-string "the-string")
user=>

HTH,

-- 
Laurent

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