Ashley Williams
Ashley Williams

Reputation: 6840

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

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

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

Upvotes: 25

Views: 7770

Answers (2)

leontalbot
leontalbot

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

Alex Ott
Alex Ott

Reputation: 87119

Something like:

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

Upvotes: 29

Related Questions