How can I define a variable in another namespace within a function/macro in Clojure? -


i'm experimenting ns in clojure, here's try:

user=> (in-ns 'some-ns) #<namespace some-ns> some-ns=> (def aa 100) #'some-ns/aa some-ns=> (in-ns 'user) #<namespace user> user=> (= some-ns/aa 100) true user=> (= user/aa 100) compilerexception java.lang.runtimeexception: no such var: user/aa, compiling:(no_source_path:5:1) ;this works expected user=> (defn function [] (in-ns 'some-other-ns) (def cc 100) (in-ns 'user)) #'user/function user=> (function) #<namespace user> user=> (= some-other-ns/cc 100) compilerexception java.lang.runtimeexception: no such var: some-other-ns/cc, compiling:(no_source_path:8:1) user=> (= user/cc 100) true 

i'm confused, why doesn't work in function? also, tried following:

user=> (binding [*ns* (create-ns 'some-a-ns)] (def dd 100)) #'user/dd user=> (= some-a-ns/dd 100) compilerexception java.lang.runtimeexception: no such var: some-a-ns/dd, compiling:(no_source_path:11:1)  user=> (= user/dd 100) true 

according clojure doc

creates , interns or locates global var name of symbol , namespace of value of current namespace (*ns*).

what i'm missing?

ps. know can use (intern 'some-ns 'a 100), want generic function/macro

(with-ns 'some-ns (def 100)) (= some/a 100) 

intern correct solution , can use in functions / macros of own. (functions can call intern; macros can expand code calling intern.)

def should ever used directly @ top level or nested within top-level forms executed top-level form is. so, def in let fine, def inside function not.

def receives special handling compiler in vars defined def forms actual created def compiled; initial bindings specified in def forms installed, however, if , when flow of control reaches def form. explains why binding example doesn't work -- compile-time value of *ns* counts, while binding introduced binding form come effect @ run time.

finally, if absolutely insist on using def forms create vars @ runtime, way eval:

(binding [*ns* some-ns]   (eval '(def foo 1)))  ;; some-ns/foo comes existence root binding of 1 

note here def occur @ top-level , executed after compilation.


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -