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

Ash*_*ams 23 clojure

我怎么能用字符串调用函数?例如:

(call "zero?" 1) ;=> false
Run Code Online (Sandbox Code Playgroud)

Ale*_*Ott 28

就像是:

(defn call [^String nm & args]
    (when-let [fun (ns-resolve *ns* (symbol nm))]
        (apply fun args)))
Run Code Online (Sandbox Code Playgroud)

  • 最好将ns-resolve与fn结合起来?检查,该符号是功能 (6认同)

leo*_*bot 15

一个简单的答案:

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

(call "zero?" 1) 
;=> false
Run Code Online (Sandbox Code Playgroud)

纯娱乐:

(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)
Run Code Online (Sandbox Code Playgroud)