25

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

(call "zero?" 1) ;=> false
1
  • It doesn't work in clojurescript. Commented Feb 20, 2019 at 0:15

2 Answers 2

29

Something like:

(defn call [^String nm & args]
    (when-let [fun (ns-resolve *ns* (symbol nm))]
        (apply fun args)))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, ns-resolve in particular was what I was looking for.
it's better also to combine ns-resolve together with fn? to check, that symbol is function
17

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.