如何在 Clojure 中从字符串定义函数?

发布于 2024-07-15 21:47:37 字数 217 浏览 8 评论 0原文

我想这样做(在 REPL 或任何地方)

(defn (symbol "print-string") [k] (println k))

,然后能够做到

(print-string "lol")

或者,如果有任何其他方法可以从宏中的自定义字符串创建 defn,您能否将我推向正确的方向?

I'd like to do this (in REPL or anywhere)

(defn (symbol "print-string") [k] (println k))

and then be able to do

(print-string "lol")

Or, if there is any other way to create defn from custom strings in macroses, could you push me into the right direction please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

月下凄凉 2024-07-22 21:47:37
(defmacro defn-with-str [string args & body]
 `(defn ~(symbol string) ~args ~@body))

(defn-with-str "print-string" [k] (println k))

(print-string "lol")
(defmacro defn-with-str [string args & body]
 `(defn ~(symbol string) ~args ~@body))

(defn-with-str "print-string" [k] (println k))

(print-string "lol")
梦里兽 2024-07-22 21:47:37

dnolen 的解决方案在宏展开时工作,而 Brian Carper 的解决方案在读取时工作。 现在,这是运行时的:

(intern *ns* (symbol "a") (fn [k] (println k)))

dnolen's solution works at macro expansion time, Brian Carper's at read-time. Now, here's one for run-time:

(intern *ns* (symbol "a") (fn [k] (println k)))
呢古 2024-07-22 21:47:37

我更喜欢 dnolen 的答案,但你也可以这样做:

(defn #=(symbol "print-string") [k] (println k))

#=() 在读取时进行评估。 我不知道 Clojure 的这个功能有多稳定,我不会依赖它在未来不会改变。 宏就是我的做法。

I like dnolen's answer better, but you can do this too:

(defn #=(symbol "print-string") [k] (println k))

#=() is evaluated at read-time. I don't know how stable a feature of Clojure this is, I wouldn't rely on it not to change in the future. Macros are how I'd do it.

霊感 2024-07-22 21:47:37

仅供参考 - dnolen 的答案仅适用于文字字符串,不适用于 def'd 或 let'd 变量中的字符串。

(defmacro defn-with-str [字符串参数和正文]
`(defn ~(符号字符串) ~args ~@body))

(def hisym "hi")
(defn-with-str hisym [] (println "hi"))

的函数

您现在有一个名为“hisym” (hi) -> java.lang.Exception:无法解析符号:在此上下文中 hi (NO_SOURCE_FILE:6)
(hisym)-> 打印“hi”

要避免这种情况,请评估宏

中的函数名称字符串
(defmacro defn-with-str [字符串参数和正文]
`(defn ~(符号(评估字符串)) ~args ~@body))

FYI - dnolen's answer will only work for literal strings, and not for strings in def'd or let'd variables.

(defmacro defn-with-str [string args & body]
`(defn ~(symbol string) ~args ~@body))

(def hisym "hi")
(defn-with-str hisym [] (println "hi"))

You now have a function called "hisym"

(hi) -> java.lang.Exception: Unable to resolve symbol: hi in this context (NO_SOURCE_FILE:6)
(hisym) -> prints "hi"

To avoid this, eval the function name string in the macro


(defmacro defn-with-str [string args & body]
`(defn ~(symbol (eval string)) ~args ~@body))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文