Clojure: allow character declaration

I get some weird behavior when checking if a character is allowed.

user=> ok CompilerException java.lang.RuntimeException: Unable to resolve symbol: ok in this context, compiling:(NO_SOURCE_PATH:0) user=> (resolve 'ok) nil user=> (if (resolve 'ok) "bla" (def ok 'ok)) "bla" user=> ok #<Unbound Unbound: #'user/ok> user=> (def ok 'ok) #'user/ok user=> ok ok 

Can someone tell me where this might come from? Is this behavior expected?

+7
source share
2 answers

(def ok "whatever") creates a variable called ok at compile time. The compiler scans the entire form to compile it, finds that you will define a variable called ok and create it for you (without binding) before your form is actually executed. When the def form is actually executed, the runtime value of the expression will be assigned to the var user/ok variable. In your example, this never happens, because var is already created, and the if branch goes the other way.

Using bound? a terrible idea as a substitute, as it checks for something completely different: does the named var (which must exist) have a constant or local stream binding.

+4
source

Since I use it only inside a macro, I use it as follows

 (defmacro bla [x] (if (resolve x) x `(def ~x '~x))) 

And now it works, since def is inside the quotation mark and evaluated after resolution.

+1
source

All Articles