我怎么能用字符串调用函数?例如像这样的东西:
(call "zero?" 1) ;=> false
答案 0 :(得分:28)
类似的东西:
(defn call [^String nm & args]
(when-let [fun (ns-resolve *ns* (symbol nm))]
(apply fun args)))
答案 1 :(得分:15)
一个简单的答案:
(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)