简体   繁体   中英

How do I create a macro to define two functions in clojure

The code below doesn't behave as I would expect.

; 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 ~@body) 
  `(defn ~(symbol (str fname "*")) ~args ~@body))

The code above doesn't create two functions as I would expect. It only creates the last one.

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

How can I get a single macro to define two functions?


; 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 ~@body)
       (defn ~(symbol (str fname "*")) ~args ~@body)))

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

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

No need to quote them separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM