2010-06-03 30 views
14

Mã bên dưới không hoạt động như tôi mong đợi.Làm cách nào để tạo macro để xác định hai hàm trong 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])) 

Đoạn mã trên không tạo ra hai chức năng như tôi mong đợi. Nó chỉ tạo ra cái cuối cùng.

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

Làm cách nào để có một macro để xác định hai hàm?

Trả lời

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

Không cần báo giá riêng biệt.

Các vấn đề liên quan