Clojure得到本地让 [英] Clojure get local lets
问题描述
如何获取使用let定义的局部变量的映射?
How can you get a map of the local variables defined using let?
(let [foo 1] (println (get (get-thread-bindings) "foo")))
; prints nil
还有另外一个功能吗?还是有一种方法从get-thread-bindings映射中提取变量?任何解决方案都应该使用嵌套的let语句。
Is there another function that does this? Or is there a way to extract the variables from the get-thread-bindings map? Any solution should work with nested let statements as well.
推荐答案
正如评论中的链接所指出的, code>& env 变量 defmacro
。根据文档:
As pointed out in the link in the comments, there's a special &env
variable available inside defmacro
. Per the documentation:
在defmacro中有两个特殊变量,用于更高级的
用法:
Two special variables are available inside defmacro for more advanced usages:
- & form - 数据)
- & env - 宏扩展点的本地绑定映射。 env映射
是从符号到包含关于
绑定的编译器信息的对象。
您可以使用此宏来编写一个宏,该宏将扩展为在扩展点处为您提供本地绑定的映射:
You can use this to write a macro that will expand to give you a mapping of local bindings at the point where the macro is expanded:
(defmacro get-env
[]
(into {} (for [k (keys &env)]
[(name k) k])))
这扩展为符号名称(name k)
到符号 k
用于所有本地绑定(keys& env)
This expands as a map of symbol name (name k)
to symbol k
for all local bindings (keys &env)
which, when evaluated, will give a map of symbol name to current binding for the symbol.
user> (get-env) ; => {}
user> (let [a 1] (get-env)) ; => {"a" 1}
user> (let [a 1 b 2]
(let [b 3 c 4] (get-env))) ; => {"c" 4, "b" 3, "a" 1}
参数:
user> (defn foo [x] (let [y 1] (get-env)))
user> (foo 2) ; => {"y" 1, "x" 2}
这篇关于Clojure得到本地让的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!