Skip to content

Instantly share code, notes, and snippets.

@vkz
Created December 15, 2015 12:39
Show Gist options
  • Save vkz/4c32cdff75ba7254ed0c to your computer and use it in GitHub Desktop.
Save vkz/4c32cdff75ba7254ed0c to your computer and use it in GitHub Desktop.
Clojure's `eval` and namespaces
;; Clojure's eval is dynamic with respect to current namespace.
;; If you ever find yourself in need of eval but want to avoid **wat**
;; moments here's hopefully an illuminating sequence:
user> (in-ns 'bla)
#namespace[bla]
bla> (refer-clojure)
nil
bla> (def x "bla")
#'bla/x
bla> (defn bleval [s]
(eval (read-string s)))
#'bla/bleval
bla> (in-ns 'dao)
#namespace[dao]
dao> (refer-clojure)
nil
dao> (def x "dao")
#'dao/x
dao> (bla/bleval "x")
"dao"
dao> (in-ns 'bla)
#namespace[bla]
bla> (defn bleval [s]
(binding [*ns* (find-ns 'bla)]
(eval (read-string s))))
#'bla/bleval
bla> (in-ns 'dao)
#namespace[dao]
dao> (bla/bleval "x")
"bla"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment