2011-03-21 193 views
1

我想創建一個clojure宏,將輸入的符號轉換爲字符串。然而,當我這樣做:Clojure宏字符串評估

(defmacro convert-to-string [something] 
    `(call-converted "~something") 
) 

(macroexpand '(convert-to-string convert-this)) 

:我得到:

(call-converted "~something") 

:不是:

(call-converted "~convert-this") 

:有沒有人告訴我,我怎麼能做到這一點?

+1

你確定這需要做個宏? – spacemanaki 2011-03-21 12:21:20

回答

4

您可以考慮使用關鍵字(或引用符號)和一個函數,而不是宏:

(defn convert-to-string [x] (call-converted (name x))) 
(convert-to-string :foo) 
(convert-to-string 'foo) 

如果你真的想要一個宏:

(defmacro convert-to-string [x] `(call-converted ~(name x))) 
(macroexpand-1 '(convert-to-string foo)) 
=> (user/call-converted "foo") 
0

我在沒有辦法對宏的專家,但這樣做解決問題:

(defmacro to-str [expr] (str expr)) 
+0

我一定是做錯了,因爲當我運行它時出現錯誤:(defmacro to-str [expr](str expr)) (macroexpand'(to-str something))as this returns something(without the引號)而不是「某些東西」(帶引號) – Zubair 2011-03-21 14:52:04