Macro Quote

I am trying to write a macro in Clojure that allows me to evaluate a number of simple "def" expressions. I am n00b when it comes to macros. The idea is that

(my-defs y1 1 y2 "taco") 

should expand to

 (do (def y1 1) (def y2 "taco")) 

The following code does this for the special case of two defs

 (defmacro my-defs [& args] `(do (def ~(first args) ~(second args)) (def ~(nth args 2) ~(nth args 3) ))) 

which is nice, but it's hard for me to generalize. I tried a few naive things related to the element binding cycle (partition 2 args) , but I always got garbage (I know this is not very specific, but the variety and degree of garbage seemed to be too much to report this here). How to do this and evaluate my definitions?

PS Macro my-defs is a toy. What I really want to do at the end is the littel helper macro for instantiating multimethods. I currently have large pieces of code that look like

 (defmethod f [AB] [x] "AB") (defmethod f [AA] [x] "AA") (defmethod f [CB] [x] "CB") 

which is a little unsightly. It would be nice if I could do something like

 (defmethods f [AB] [x] "AB" [AA] [x] "AA" [CB] [x] "CB") 

instead of this.

+6
source share
1 answer

It seems to me that you are looking for a macro ~ @ macro / unquote.

 (defmacro defmethods [n & defs] `(do ~@ (map (fn [[a1 a2 a3]] `(def ~n ~a1 ~a2 ~a3)) (partition 3 defs)))) 
+5
source

Source: https://habr.com/ru/post/896670/


All Articles