5
votes

I am stuck on a seemingly basic thing. I have a namespace where I have some definitions:

(ns my-namespace)

(def my-definition "HELLO")
(def my-definition2 "HI")

Now, I want to use the value of the vars in my-namespace in a macro, but I want to retrieve the symbols dynamically. E.g.,

(defmacro my-macro [n]
  (-> "my-namespace/my-definition" symbol resolve var-get))

Retrieving a symbol in such a manner works in a function (as long as the namespace is loaded), but not in a macro.

In a macro, the symbol cannot be resolved. I've tried quoting and unquoting but it still does not work.

Is it possible in a macro to use the value of a symbol created like that? If so, how?

2
my-namespace needs to be loaded before my-macro is expanded. Is this so? - OlegTheCat
Adding (require [my-namespace :refer :all]) to the macro namespace declaration solved the problem. If you post an answer you can score some points @OlegTheCat, if you're interested in that. - Erwin Rooijakkers

2 Answers

4
votes

Try this one:

(defmacro my-macro
  [str]
  (-> str symbol resolve deref))
2
votes

The symbol cannot be resolved, because the namespace where it is defined is not loaded. You can load namespace by

(require 'my-namespace)

or in namespace declaration:

(ns macro-expansion-ns
  (:require [my-namespace]))