user2609980
user2609980

Reputation: 10484

Resolve symbol in macro

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?

Upvotes: 5

Views: 569

Answers (2)

OlegTheCat
OlegTheCat

Reputation: 4513

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]))

Upvotes: 2

Ertuğrul Çetin
Ertuğrul Çetin

Reputation: 5231

Try this one:

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

Upvotes: 4

Related Questions