clojure - eval code in different namespace

一个人想着一个人 提交于 2019-12-03 06:30:34

Solved:

(binding [*ns* user-ns] (eval (read-string request)))

Changing namespace means that you will have to reinitialize all the aliases, or refer to even clojure.core stuff with a fully qualified name:

user=> (defn alien-eval [ns str]
         (let [cur *ns*]
           (try ; needed to prevent failures in the eval code from skipping ns rollback
             (in-ns ns)   
             (eval (read-string str))
             (finally 
               (in-ns (ns-name cur))
               (remove-ns ns))))) ; cleanup, skip if you reuse the alien ns
#'user/alien-eval
user=> (alien-eval 'alien "(clojure.core/println clojure.core/*ns*)") ; note the FQN
#<Namespace alien> ; the effect of println
nil                ; the return value of alien-eval

(symbol (str "client-" (Math/abs (.nextInt random)))

I just wanted to add, that this could be achieved with

(gensym "client-")

(I wanted to comment, but it turns our that I can't :))

You can write a macro that mimics

(defmacro my-eval [s] `~(read-string s))

It works better that eval because the symbol resolution of s occurs in the context that calls my-eval. Thanks to @Matthias Benkard for the clarifications.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!