I’m trying to write a macro that builds middleware akin to that used in compojure.
I want to be able to call:
(def-middleware plus-two [x]
(+ 2 x))
And have the result look like:
(defn plus-two [f]
(fn [x]
(f (+ 2 x)))
I’ve got this far from reading on-line guides but it’s not working out for me:
(defmacro def-middleware [fn-name args & body]
'(defn ~fn-name [f]
(fn ~args
(f ~@body))))
Any help or a pointer to a better macro writing guide would be great, thanks.
Let’s see what
macroexpand-1gives us:Not precisely what we’re after! First things first: if you want to unquote things in a macro, you need to use “`” (the quasiquote/syntax-quote operator), not “‘”. Also, I’m not sure what you’re after with those dollar signs, but it might be that you’re going for the clojure’s handy shortcut for using
gensymfor hygiene. But you need it immediately after each identifier you use it with (so[f#], not[f]$), and you need it on each occurrence of the identifier. And you don’t need it withargs. Putting all this together: