使用Clojure中函数名称的字符串调用函数

问题描述:

如何使用字符串调用函数?例如是这样的:使用Clojure中函数名称的字符串调用函数

(call "zero?" 1) ;=> false 

一个简单的回答:

(defn call [this & that] 
    (apply (resolve (symbol this)) that)) 

(call "zero?" 1) 
;=> false 

只是为了好玩:

(defn call [this & that] 
    (cond 
    (string? this) (apply (resolve (symbol this)) that) 
    (fn? this)  (apply this that) 
    :else   (conj that this))) 

(call "+" 1 2 3) ;=> 6 
(call + 1 2 3) ;=> 6 
(call 1 2 3)  ;=> (1 2 3) 

喜欢的东西:

(defn call [^String nm & args] 
    (when-let [fun (ns-resolve *ns* (symbol nm))] 
     (apply fun args))) 
+1

谢谢'NS-resolve'在特别是我正在寻找的东西。 – 2010-10-03 10:28:52

+6

最好是将ns-resolve与fn结合使用?检查,该符号是功能 – 2010-10-03 17:22:57