4

I have a function a defined as

(defn a [] "Hello")

I have another variable which b

(def b "a")

I would like to call the function represented by the string value of 'b', ie 'a' should be called. How do I do that?

1

1 Answer 1

11

You need to convert it into a symbol and then resolve it:

user=> ((resolve (symbol b)))
"Hello"

user=> ((-> b symbol resolve))
"Hello"

Just to clarify a little, here is a slightly more verbose solution:

(let [func (-> b symbol resolve)]
  (func arg1 arg2 arg3)) ; execute the function
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for the answer, had another question. Why do I need to 'resolve' it also. Why cant I just do ((symbol b))? If I can call other symbols directly (a) then why cant I do this also ((symbol b))?
also is it possible to pass params in the form with thrush operator?
No, you cannot 'call' a symbol. What you refer to as 'call symbols directly' in fact is not calling symbols. When you execute (symbol b) you will get symbol object, and when you execute simply a, you will get an object to which a refer, a function in your case. Calling symbol objects makes sense only for looking up keys in map: ((symbol "a") {'a 1 'b 2}) returns 1. And resolve function does exactly what you need, that is, tries to resolve an object behind the symbol. In fact a and (resolve 'a) expressions are nearly equivalent (except for namespaces, but that's another topic).
And yes, it is possible to pass parameters to the said form. Did you notice double parentheses? Inner ones are equivalent in term of their returning value, so these calls will get the same result: ((resolve (symbol b)) 1 2) and ((-> b symbol resolve) 1 2). In fact the latter is transformed by the macro processor into the former.

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.