Clojure:如何在运行时创建函数 [英] Clojure: How to create a function at runtime
问题描述
我想在运行时完全生成一个fn(即名称和arg符号是在运行时确定的,而不是在代码中确定的)实现此目标的最佳方法是什么?
I want to generate a fn totally at runtime (i.e. the name and the arg symbols are decided at runtime, not in code) What's the best way to achieve this ?
例如,如何实现以下功能?
For example how can I implement the following function ?
(defn gen-fn [name arg-symbols body]
...
...
将被这样使用:
(gen-fn "my-func-name" (symbol "x") (symbol "y") (println "this is body. x=" x))
请注意,函数名称,args和主体均未编码,但可以在运行时确定
Note that function name, the args and the body are not coded but can be decided at runtime
推荐答案
(defn gen-fn
[n as b]
(let [n (symbol n)
as (vec (map symbol as))
fn-value (eval `(fn ~n ~as ~b))]
(intern *ns* n fn-value)))
还有一些用途:
user=> (gen-fn "foo" ["x"] '(do (println x) (println (inc x))))
#'user/foo
user=> (foo 5)
5
6
nil
但是,我不太喜欢这种方法.闻起来真难闻: eval
.为什么要在运行时生成全局变量?我看到各种错误的命名空间和其他丑陋的问题不断涌现……
However, I don't really like this approach. It smells really hard: eval
. Why do you want to generate globals at runtime? I see various problems with wrong namespaces and other ugly hiccups rising at the horizon...
这篇关于Clojure:如何在运行时创建函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!