A function call when its name is stored as a string value

I have a function defined as

(defn a [] "Hello") 

I have another variable that b

 (def b "a") 

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

+4
source share
1 answer

You need to convert it to symbol , and then resolve it:

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

To clarify a bit, here is a slightly more detailed solution:

 (let [func (-> b symbol resolve)] (func arg1 arg2 arg3)) ; execute the function 
+10
source

Source: https://habr.com/ru/post/1432627/


All Articles