Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you force a Clojure macro to evaluate its arguments?

Tags:

macros

clojure

I'm trying to define a helper function that wraps clojure.test/deftest. Here's my general idea:

(defn test-wrapper
  [name & body]
  (deftest (symbol (clojure.string/replace name #"\W" "-")) body)))

However, since the first argument to deftest is unevaluated, it throws an exception since it is a form and not a symbol. Is there any way to force the form to evaluate first?

like image 920
mybuddymichael Avatar asked Feb 18 '23 02:02

mybuddymichael


1 Answers

The better approach here is to make test-wrapper a macro. Macros don't evaluate their arguments, unless you tell them to. You can manipulate the arguments and substitute them in some generated code, as follows:

(use 'clojure.test)

(defmacro test-wrapper
  [name & body]
  (let [test-name (symbol (clojure.string/replace name #"\W" "-"))]
    `(deftest ~test-name ~@body)))

(test-wrapper "foo bar" (is (= 1 1)))

(run-tests)
like image 157
Michiel Borkent Avatar answered Mar 02 '23 19:03

Michiel Borkent