(def v-2 "this is v2") user=> (defmacro m [v] (symbol (str "v-"-6ren">
gpt4 book ai didi

clojure - 如何编写 Clojure 宏来获取 var 的值?

转载 作者:行者123 更新时间:2023-12-05 08:41:12 25 4
gpt4 key购买 nike

user=> (def v-1 "this is v1")
user=> (def v-2 "this is v2")
user=> (defmacro m [v] (symbol (str "v-" v)))
user=> (m 1)
"this is v1"
user=> (m 2)
"this is v2"
user=> (let [i 2] (m i))
CompilerException java.lang.RuntimeException: Unable to resolve symbol: v-i in this context, compiling:(NO_SOURCE_PATH:73:12)

我可以写一个宏让两者都让吗

(m 2)

(let [i 2] (m i))

获取“这是 v2”?

最佳答案

这可以不用宏:

(defn m [v] (var-get (resolve (symbol (str "v-" v)))))

(m 1) ;; => "This is v1"
(let [i 2] (m i)) ;; => "This is v2"

如果需要,您也可以使用宏:

(defmacro m [v] `@(resolve (symbol (str "v-" ~v))))

关于clojure - 如何编写 Clojure 宏来获取 var 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51604260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com