2010-06-03 59 views
14

下面的代碼不像我預期的那樣運行。如何創建一個宏來定義clojure中的兩個函數

; given a function name, its args and body, create 2 versions: 
; i.e., (double-it foo []) should create 2 functions: foo and foo* 
(defmacro double-it    
    [fname args & body]  
    `(defn ~fname ~args [email protected]) 
    `(defn ~(symbol (str fname "*")) ~args [email protected])) 

上面的代碼並沒有像我期望的那樣創建兩個函數。它只創建最後一個。

user=> (double-it deez [a b] (str b a)) 
#'user/deez* 

如何獲得單個宏來定義兩個函數?

回答

14
 

; given a function name, its args and body, create 2 versions: 
; ie (double-it foo []) should create 2 functions: foo and foo* 
(defmacro double-it     
    [fname args & body]   
    `(do (defn ~fname ~args [email protected]) 
     (defn ~(symbol (str fname "*")) ~args [email protected]))) 

(double-it afunc [str] (println str)) 

(afunc* "asd") 
(afunc "asd") 
 

無需單獨引用它們。

相關問題