2
votes

I have the following macro:

(defmacro anon-mac [value]
  #(+ value 1))

I would expect for this to behave as such:

((anon-mac 1) 1) ;=> 2

However I get this error:

IllegalArgumentException No matching ctor found for class user$anon_mac$fn__10767  clojure.lang.Reflector.invokeConstructor (Reflector.java:163)

What should I do to be able to have this macro return an anonymous function that works as I would expect?

The answer must be a macro. Seeing as my question concerns the ability of macros to return anonymous functions

Why must the answer be a macro? In my case it is because I do not want this conversion to be called more than once at compile time wherever it is found. If I were to have this conversion in a for loop that called it 200 times, with a function the conversion would be run 200 times. However seeing as macros edit the code itself it would only be run once for that for loop.

2

2 Answers

3
votes

I simply needed to escape the function while evaluating the inner variable like so:

(defmacro anon-mac [value] `#(+ % ~value))
3
votes

Not sure what you are using it for, but if you wanted to go with a function, you might find partial helpful, as it provides the behavior that you are after.

(defn anon-partial [val] (partial + val))
((anon-partial 1) 1) ;;=> 2

There are also some helpful examples of partial at clojuredocs.org.