Reputation: 6840
How could I call a function with a string? e.g. something like this:
(call "zero?" 1) ;=> false
Upvotes: 25
Views: 7770
Reputation: 2543
A simple answer:
(defn call [this & that]
(apply (resolve (symbol this)) that))
(call "zero?" 1)
;=> false
Just for fun:
(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)
Upvotes: 17
Reputation: 87119
Something like:
(defn call [^String nm & args]
(when-let [fun (ns-resolve *ns* (symbol nm))]
(apply fun args)))
Upvotes: 29