Calling a Function From a String With the Function’s Name in Clojure

Viewed 7205

How could I call a function with a string? e.g. something like this:

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

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)
Related