Clojure: function / signature arguments using macro or def

I have many functions of the same long signature (abbreviated here for simplicity):

(defn f [x & {:keys [abcdefgh] :or [a false b false c false d false e false f false g false h false]}] a) 

I was hoping to use a macro, function, or even def to store this shared signature in advance:

 (def args `[abcdefgh]) (defn args [] `[abcdefgh]) (defmacro args [] `[abcdefgh]) 

but all of them when I'm connected to

 (defn f [x & {:keys (args) :or [a false b false c false d false e false f false g false h false]}] a) 

ended in errors for example

 CompilerException java.lang.RuntimeException: Unable to resolve symbol: a in this context, compiling:(NO_SOURCE_PATH:1) 

So my two questions:

  • Is there a way to define and use such generic args ?

  • If such args can be defined, I would also like to reduce it to get the parameters :or : [a false b false c false d false e false f false g false h false] . How will this be done? (I ask if the working definition of args can be so strange that it is no longer easy.)

+4
source share
1 answer

The problem is that the material inside the argument vector in defn not evaluated. However, you can define your own version of defn , for example:

 user=> (defmacro mydefn [name & body] `(defn ~name ~'[abc] ~@body )) #'user/mydefn user=> (mydefn f (+ ab)) #'user/f user=> (f 1 2 4) 3 

Note the need ~' for arguments. Otherwise, the quotation mark ( ` ) qualifies characters in user.a , etc.

+6
source

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


All Articles