Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 370
Nick Orton Avatar asked Jun 03 '10 12:06

Nick Orton


1 Answers


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

like image 108
Hamza Yerlikaya Avatar answered Oct 11 '22 14:10

Hamza Yerlikaya